2014-11-03 22 views
4

一個字段篩選:Django的在考慮從Django的投票教程以下車型的外鍵對象

class Question(models.Model): 
    question_text = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published') 

    def __str__(self): 
     return self.question_text 

    def was_published_recently(self): 
     now = timezone.now() 
     return now - datetime.timedelta(days=1) <= self.pub_date <= now 
    was_published_recently.admin_order_field = 'pub_date' 
    was_published_recently.boolean = True 
    was_published_recently.short_description = 'Published recently' 


class Choice(models.Model): 
    question = models.ForeignKey(Question) 
    choice_text = models.CharField(max_length=200) 
    votes = models.IntegerField(default=0) 

    def __str__(self): 
     return self.choice_text 

我希望能夠排除沒有問題,並選擇類似建議的教程。我一直在玩弄過濾器,但我無法弄清楚,我想:

def get_queryset(self): 
    return Question.objects.filter(pub_date__lte=timezone.now(), choice__count__gt=0) 

,但我發現

Relation fields do not support nested lookups 

我如何通過沒有任何問題過濾選擇?

回答

8

您也可以使用如下

from django.db.models import Count 

...... 

def get_queryset(self): 
    return Question.objects.annotate(num_choice=Count('choice')).filter(pub_date__lte=timezone.now(), num_choice=0) 
+0

這似乎更好,因爲它允許我通過任意數量的選項(如2或更多)進行過濾,而其他答案只會告訴我是否有一些或0個選項 – Jake 2014-11-03 06:45:09

2

使用choice__isnull = True,其中choice_name是related_name。

def get_queryset(self): 
    return Question.objects.filter(pub_date__lte=timezone.now(), choice__isnull=False) 
1

您需要使用choice__isnull=False,而不是指望像

return Question.objects.filter(pub_date__lte=timezone.now(), 
           choice__isnull=False) 

請注意,你可能會得到重複記錄,您可以使用整合.distinct()

+0

這工作,但如果我能如果我想通過只有一些任意選擇的問題來改變它來過濾,我會如何實現這一點? – Jake 2014-11-03 06:34:24

0

我將模型更改爲類似:

class Question(models.Model): 
    choices = models.ManyToManyField('Choice') 
    ... 

class Choice(models.Model): 
    question = models.ForeignKey(Question) 
    ... 

查詢會像

questions = Question.objects.annotate(num_of_choices=Count('choices')).filter(pub_date__lte=timezone.now(), num_of_choices=0) 
+0

現在你在這些對象之間有兩個關係,其中一個是多餘的。相反,你可以在Choice.question的'choices'中的FK上添加顯式的related_name。 – mkoistinen 2016-04-07 13:47:28