0

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新しい選択肢を作成せずに出力を得る方法はありますか?

- 前もって感謝します

4

1 に答える 1

3

c = p.choice_set.filter(id=3)単一選択オブジェクトを返しません。同じ ID を持つオブジェクトは 1 つしかないため、1 つの選択オブジェクトで構成されるクエリセットが返されます。クエリセットは iterable です。つまり、その変数から選択オブジェクトを取得したい場合は、次のようにする必要があります。c = p.choice_set.filter(id=3)[0] これが との違いchoice_set.createです。 create は、作成された単一のオブジェクトを返します。

さて、それはそれを行う方法ではありません。単一のオブジェクトに対してクエリを実行していることがわかっている場合は、get を使用します。 c = p.choice_set.get(id=3).

詳細については、クエリのドキュメントを参照してください。

于 2013-05-14T14:10:10.413 に答える