python27+django1.9 Add API

Source: Internet
Author: User

We go into Python's interactive shell and use the Django-provided API. To enter the Python shell, use the Python manage.py shell

Using this instead of simply typing "python" is because manage.py will help you create the environment for your project. The Create Project environment consists of two things:
    • Add the polls to the Sys.path. For flexibility, the modules in Django are referenced by a dotted path (e.g. ' polls.models '). In order to achieve this, the polls package must be in the Sys.path.
      We've come across an example of this: the list in the Installed_apps setting is using the point path notation.
    • Set the DJANGO_SETTINGS_MODULE environment variable to specify the path to your settings.py file for Django.

Omit manage.py

In the shell, you can explore the database API, which can be used to verify that the model can be called correctly
>>> from polls.models import Poll, Choice # Imports The model we just wrote.
# There are no poll in the system.
>>> Poll.objects.all ()
[]
# Create a new poll.
>>> Import datetime
>>> p = Poll (question= "What's Up?", Pub_date=datetime.datetime.now ())
# Save the object in the database. You need to explicitly call save ().
>>> P.save ()

From Start.models import StartStart.objects.all () Import DATETIMEP = Start (question= "What's Up?", pub_date= Datetime.datetime.now ()) P.save ()

That is, the contents of the above code box, in turn, input processing, no matter what prompted, as long as the database generated tables, the basic is successful

# Now it has an ID. Note that this may also show 1L instead of 1, and
# depends on what database you are using. But there's nothing wrong with that,
# It just means that the database is more inclined to return an integral type to Python's Long integer object.
>>> p.id
1
# Access database columns via Python properties
>>> p.question
"What's Up?"
>>> p.pub_date
Datetime.datetime (7, Min, XX, +)
# Modify the value by modifying the property, and then call Save ().
>>> p.pub_date = Datetime.datetime (4, 1, 0, 0)
>>> p.save ()
# Objects.all () Displays all poll of the database.
>>> Poll.objects.all ()
[<poll:poll Object>] and so on. <poll:poll object> does not show any useful information about this object at all. We can edit the Poll model (in file polls/models.py) to add a __unicode__ () method to Poll and Choice to solve this problem:
Class Poll (models. Model):
# ...
def __unicode__ (self):
return Self.question
Class Choice (models. Model):
# ...
def __unicode__ (self):
return Self.choice It is necessary to add the __unicode__ () method to your model. Not only to make yourself better at understanding interactive cues, but also because the use of the object's performance runs through the entire Django auto-generated admin. Why is the
__unicode__ () instead of __str__ ()?

If you're familiar with Python, you might prefer to add __str__ () to your class instead of the __unicode__ () method. We use __UNICODE__ () here because the Django model uses Unicode by default, and all data stored in the database is converted to Unicode when it returns.

The Django model has a default __str__ () method called __unicode__ (), which converts the result set into a UTF-8 byte string. In each meaning Unicode (p) Returns a Unicode string, and STR (p) returns a normal UTF-8 encoded string.

If you still feel confused, remember to add the __unicode__ () method to your model, and if you're lucky, everything will work as you want.

Note that these are common python methods, let's add a custom method to use as a demonstration:
Import datetime
# ...
Class Poll (models. Model):
# ...
def was_published_today (self):
return self.pub_date.date () = = Datetime.date.today () Adding an import datetime references a Python datetime module. Save these changes and then run the Python manage.py Shell to open a new Python interactive shell:
>>> from polls.models import Poll, Choice
# Make sure our newly added __unicode__ () is working properly.
>>> Poll.objects.all ()
[<poll:what ' s up?>]
# Django provides a rich database lookup API,
# These APIs are driven entirely by keyword parameters.
>>> Poll.objects.filter (id=1)
[<poll:what ' s up?>]
>>> Poll.objects.filter (question__startswith= ' what ')
[<poll:what ' s up?>]
# Get a poll with a year of 2007.
>>> Poll.objects.get (pub_date__year=2007)
<poll:what ' s up?>
>>> Poll.objects.get (id=2)
Traceback (most recent):
...
Doesnotexist:poll matching query does not exist.
# Search by primary key is a very common way,
# so Django provides a convenient way to find this method.
# below is equivalent to Poll.objects.get (id=1).
>>> Poll.objects.get (pk=1)
<poll:what ' s up?>
# Verify that our custom method works correctly.
>>> p = Poll.objects.get (pk=1)
>>> P.was_published_today ()
False
# Add a few choice to poll.
# Call the CREATE function to create the choice object, call the INSERT statement,
# Add the choice to the saved choice collection and return the newly created choice object.
# Django creates a collection to hold the Foreign Key Association, which can be accessed through the API.
>>> p = Poll.objects.get (pk=1)
# all choice--associated with the display are not currently available.
>>> P.choice_set.all ()

python27+django1.9 Add API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.