python Django 1.7 中文入门 (官网) 08 Django API 2

shell API的功能主要是用来调试,实时反馈。也要可以用来数据查询等。

方法/步骤

  1. 重新运行python manage.py shell

    1、首先要导入数据库模块

    >>> from polls.models import Question, Choice

  2. 确定models.py已经添加__str__()函数,并且已经运行。

    >>> Question.objects.all()

    [<Question: What's up?>, <Question: What's new?>]

    使用Question.objects.all(),可以返回数据表的数据。

  3. 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’开头的内容。

  4. 通过主键查询是最普通的方式,所以Django提供了一种快捷方式,

    下面的这个代码和Question.objects.get(id=1)

    >>> Question.objects.get(pk=1)

    <Question: What's up?>

  5. 确认我们自定义的方法was_published_recently()生效。

    >>> q = Question.objects.get(pk=1)

    >>> q.was_published_recently()

    True

  6. 给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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值