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>)

#
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值