shell API的功能主要是用来调试,实时反馈。也要可以用来数据查询等。
方法/步骤
-
重新运行python manage.py shell
1、首先要导入数据库模块
>>> from polls.models import Question, Choice
-
确定models.py已经添加__str__()函数,并且已经运行。
>>> Question.objects.all()
[<Question: What's up?>, <Question: What's new?>]
使用Question.objects.all(),可以返回数据表的数据。
-
Django提供丰富的数据库查询API,全部由关键字参数驱动。
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
filter(id=1)用来筛选指定参数。
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>, <Question: What's new?>]
question_text__startswith由两部分组成,字段:question_text 后缀关键字:__startswith.
question_text__startswith='What'作用是:筛选指定字段,以‘What’开头的内容。
-
通过主键查询是最普通的方式,所以Django提供了一种快捷方式,
下面的这个代码和Question.objects.get(id=1)
>>> Question.objects.get(pk=1)
<Question: What's up?>
-
确认我们自定义的方法was_published_recently()生效。
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
-
给Question添加几个选项,需要构建一个Choice对象,插入声明,添加选择到设置有效的选项,
并且返回新Choice对象。Django创建一套另一个类的ForeignKey relation.
>>> q = Question.objects.get(pk=1)
从关联对象设置中显示任意选项
>>> q.choice_set.all()
[]
创建3个选项
>>> 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对象有一个API通道和Question对象关联。
>>> c.question
<Question: What's up?>
反过来亦然,Question对象获得一个通道到Choice对象
>>> q.choice_set.all()
通过count()函数可以取得选项数量。
>>> q.choice_set.count()
删除选项:
>>> q.choice_set.all()
3849

被折叠的 条评论
为什么被折叠?



