现在,让我们跳到交互式的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>) #