2013-05-14 87 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)不會返回一個選擇對象。它返回由單個選擇對象組成的查詢集,因爲顯然只有一個具有相同ID的對象。查詢集是iterables,這意味着如果你想獲得該變量的選擇對象應該是:c = p.choice_set.filter(id=3)[0] 這是choice_set.create的區別是:創造回報單創建的對象。

現在,這不是做到這一點的方法。當你知道你正在查詢單個對象時,使用get。 c = p.choice_set.get(id=3)

進一步詳情,請參閱querying documentation

+0

感謝您的支持。我很感激。 – 2013-05-14 14:18:06