django 框架API 调用
现在,让我们跳到交互式的Python shell中,并使用Django提供的免费API。要调用Python shell,请使用以下命令: python manage.py shell
我们使用它,而不是简单地输入“python”,因为 manage.py 设置了 DJANGO_SETTINGS_MODULE 环境变量,它为Django提供了Python 的导入路径到您的 mysite/settings.py 文件。
如果你不愿意使用 manage.py 没问题。只需将 DJANGO_SETTINGS_MODULE 环境变量设置 mysite.settings,启动一个普通的Python shell,并设置 Django:
用pycharm 打开之前的django项目, 点击 terminal 输入以下内容
python manage.py shell
import django
django.setup()

如果这引起了AttributeError,那么您可能使用的是一个与本教程版本不匹配的Django版本。你会想要切换到旧的教程或更新的Django版本。
您必须从同一个目录管理中运行manage.py 在,或者确保目录位于Python路径上,因此导入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() <QuerySet []> # 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. >>> 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() <QuerySet [<Question: Question object (1)>]>
等一下。<Question: Question object (1)> 不是这个对象的一个有用的表示。让我们通过编辑 Question model (in the polls/models.py file) and adding a __str__() method to both Question and Choice:
polls/models.py from django.db import models class Question(models.Model): # ... def __str__(self): return self.question_text class Choice(models.Model): # ... def __str__(self): return self.choice_text
向您的模型添加 __str__() 方法是很重要的,不仅是为了在处理交互式提示时方便,而且因为在Django的自动生成的管理中使用了对象的表示。
注意,这些是常规的Python方法。让我们添加一个自定义方法,只是为了演示:
polls/models.py 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 模块和Django在 django.utils.timezone中与时间相关的实用工具。分别时区。如果您不熟悉Python中的时区处理,您可以在时区支持文档中了解更多信息。
保存这些更改,并通过运行命令实现 python manage.py shell
>>> from polls.models import Question, Choice # Make sure our __str__() addition worked. >>> Question.objects.all() <QuerySet [<Question: What's up?>]> # Django provides a rich database lookup API that's entirely driven by # keyword arguments. >>> Question.objects.filter(id=1) <QuerySet [<Question: What's up?>]> >>> Question.objects.filter(question_text__startswith='What') <QuerySet [<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() <QuerySet []> # 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() <QuerySet [<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) <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]> # Let's delete one of the choices. Use delete() for that. >>> c = q.choice_set.filter(choice_text__startswith='Just hacking') >>> c.delete()
有关模型关系的更多信息,请参阅访问相关对象。关于如何使用双重下划线来通过API执行字段查找,请参阅字段查找。有关数据库API的详细信息,请参阅我们的数据库API引用。
介绍了Django管理
哲学
python manage.py createsuperuser
输入您想要的用户名并按Enter。 Username: admin 然后你会被提示输入你想要的电子邮件地址:Email address: admin@example.com
最后一步是输入您的密码。您将被要求两次输入您的密码,第二次是确认第一次的密码。
Password: ********** Password (again): ********* Superuser created successfully.
启动开发服务器
Django管理站点在缺省情况下被激活。让我们启动开发服务器并探索它。
如果服务器没有运行,那么启动它:
python manage.py runserver
现在,打开一个Web浏览器和去“/ admin /”在本地域中——例如,http://127.0.0.1:8000 / admin /。您应该看到管理员的登录屏幕:

由于默认情况下翻译是打开的,登录屏幕可能会显示在你自己的语言中,这取决于你的浏览器的设置,如果Django有这种语言的翻译。
进入管理网站
现在,尝试使用前面步骤中创建的超级用户帐户登录。您应该看到Django管理索引页面:

您应该看到一些类型的可编辑内容:组和用户。这是由django.contrib.auth提供的。Django的身份验证框架。

浙公网安备 33010602011771号