Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django filtering on a field in a foreign key object

Tags:

python

django

Given the following models from the django polls tutorial:

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

I want to be able exclude questions without and choices like suggested in the tutorial. I've been playing around with Filter but I can't figure it out, I tried:

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

but I'm getting

Relation fields do not support nested lookups

How can I filter by Questions that do not have any Choices?

like image 486
Jake Avatar asked Dec 19 '22 09:12

Jake


2 Answers

You can also use like below

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)
like image 150
sajadkk Avatar answered Dec 22 '22 10:12

sajadkk


Use choice__isnull=True, where choice is the related_name.

def get_queryset(self):
    return Question.objects.filter(pub_date__lte=timezone.now(), choice__isnull=False)
like image 41
Geo Jacob Avatar answered Dec 22 '22 11:12

Geo Jacob