2013-05-14 5 views
0

Я снова создаю приложение «Опросы» в Django Docs. Я хотел снова спросить об одной конкретной вещи, которую они делают в базе данных django. Код показан ниже: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, чтобы дать вам результат без необходимости создавать новый выбор?

- Заранее спасибо

ответ

3

c = p.choice_set.filter(id=3) не будет возвращать один объект выбора. Он возвращает набор запросов, состоящий из одного объекта выбора, потому что, очевидно, существует только один объект с одним и тем же идентификатором. Querysets являются итерабельными, что означает, что если вы хотите получить объект выбора из этой переменной, это должно быть: c = p.choice_set.filter(id=3)[0] В этом разница с choice_set.create: create возвращает единственный созданный объект.

Теперь это не способ сделать это. Когда вы знаете, что вы запрашиваете для одного объекта, используйте get. c = p.choice_set.get(id=3).

Дополнительную информацию см. На сайте querying documentation.

+0

Спасибо за это. Я ценю это. –

Смежные вопросы