【问题标题】:Django Database querying differencesDjango 数据库查询差异
【发布时间】:2013-05-14 13:55:49
【问题描述】:

我正在 Django Docs 中再次创建 Polls 应用程序。我想再次询问他们在 django 数据库中所做的一件特别的事情。代码如下:

>>> from polls.models import Poll, Choice

# Make sure our __unicode__() addition worked.
>>> Poll.objects.all()
[<Poll: What's up?>]

# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Poll.objects.filter(id=1)
[<Poll: What's up?>]
>>> Poll.objects.filter(question__startswith='What')
[<Poll: What's up?>]

# Get the poll that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Poll.objects.get(pub_date__year=current_year)
<Poll: What's up?>

# Request an ID that doesn't exist, this will raise an exception.
>>> Poll.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Poll matching query does not exist. Lookup parameters were {'id': 2}

# 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 Poll.objects.get(id=1).
>>> Poll.objects.get(pk=1)
<Poll: What's up?>

# Make sure our custom method worked.
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_recently()
True

# Give the Poll 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 poll's choices) which can be accessed via the API.
>>> p = Poll.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
[]

# Create three choices.
>>> p.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> p.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = p.choice_set.create(choice_text='Just hacking again', votes=0)

# Choice objects have API access to their related Poll objects.
>>> c.poll
<Poll: What's up?>

如果您查看变量c,您会发现它是使用p.choice_set.create(choice_text='Just hacking again', votes=0) 创建的。现在,如果你用这个来创建它:c = p.choice_set.filter(id=3),当你输入c.poll 时,它会给你一个错误。为什么会这样?控制台给了我这个错误:AttributeError: 'Poll' object has no attribute 'create',但我不明白这是什么意思。

另外,有没有办法让c.poll 给你一个输出而不必创建一个新的选择?

-- 提前致谢

【问题讨论】:

    标签: django django-database


    【解决方案1】:

    c = p.choice_set.filter(id=3) 不会返回单个选择对象。它返回一个由单个选择对象组成的查询集,因为显然只有一个具有相同 id 的对象。查询集是可迭代的,这意味着如果您想从该变量中获取选择对象,它应该是:c = p.choice_set.filter(id=3)[0] 这就是与choice_set.create 的区别:create 返回单个创建的对象。

    现在,这不是这样做的方法。当您知道要查询单个对象时,请使用 get。 c = p.choice_set.get(id=3).

    更多详情请参阅querying documentation

    【讨论】:

    • 谢谢。我很感激。
    猜你喜欢
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多