现在,让我们进入Python的交互式shell,玩转这些Django提供给你的API。 使用如下命令来调用Python shell:
$ python manage.py shell
我们使用上述命令而不是简单地键入“python”进入python环境,是因为manage.py 设置了DJANGO_SETTINGS_MODULE 环境变量,该变环境变量告诉Django导入mysite/settings.py文件的路径。
绕开 manage.py
如果你不想使用manage.py,也没问题。只要设置DJANGO_SETTINGS_MODULE 环境变量为 mysite.settings,启动一个普通的Python shell,然后建立Django:
>>> import django
>>> django.setup()
如果以上命令引发了一个AttributeError,可能是你使用了一个和本教程不匹配的Django版本。 你可能需要换一个老一点的教程或者换一个新一点的Django版本。
你必须在与manage.py相同的目录下运行python,或确保你的目录在Python 的路径中,这样import mysite才可以工作。
所有这些信息,请参见django-admin 的文档。
一旦你进入这个shell,请探索这些数据库 API:
>>> from polls.models import Question, Choice # Import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all()
[]
# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
# Save the object into the database. You have to call save() explicitly.
>>> q.save()
# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> q.id
1
# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()
# objects.all() displays all the questions in the database.
>>> Question.objects.all()
[<Question: Question object>]
先等一下。<Question: Question object>对于这个对象是一个完全没有意义的表示。 让我们来修复这个问题,编辑Question模型(在polls/models.py文件中)并添加一个__str__()方法给Question和Choice:
from django.db import models
class Question(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.question_text
class Choice(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.choice_text
给你的模型添加__str__()方法很重要,不仅会使你自己在使用交互式命令行时看得更加方便,而且会在Django自动生成的管理界面中使用对象的这种表示。
__str__ 还是 __unicode__?
对于Python 3来说,这很简单,只需使用__str__()。
对于Python 2来说,你应该定义__unicode__()方法并返回unicode 值。Django 模型具有一个默认的__str__() 方法,它会调用__unicode__()并将结果转换为UTF-8 字节字符串。这意味着unicode(p)将返回一个Unicode 字符串,而str(p)将返回一个字节字符串,其字符以UTF-8编码。Python 的行为则相反:对象的__unicode__方法调用 __str__方法并将结果理解为ASCII 字节字符串。这个不同点可能会产生困惑。
如果以上这些令你费解的话,那就使用Python 3吧。
请注意这些都是普通的Python方法。 让我们演示一下如何添加一个自定义的方法:
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
注意import datetime 和from django.utils import timezone分别引用Python 的标准datetime 模块和Djangodjango.utils.timezone中时区相关的工具。如果你不了解Python中时区的处理方法,你可以在时区支持的文档 中了解更多的知识。
保存这些改动,然后通过python manage.py shell再次打开一个新的Python 交互式shell:
>>> from polls.models import Question, Choice
# Make sure our __str__() addition worked.
>>> Question.objects.all()
[<Question: What's up?>]
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>]
# Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
# Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist.
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?>
# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
[]
# Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
# Choice objects have API access to their related Question objects.
>>> c.question
<Question: What's up?>
# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3
# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
# Let's delete one of the choices. Use delete() for that.
>>> c = q.