M. Hosseini
M. Hosseini

Reputation: 63

How can I filtering objects of a model that their foriegn keys are not null in django?

I have these two models:

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

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

and in views.py I want to return just 5 last questions that have choice. In other words questions without any choice don't return. my view:

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

What change should I apply in return statement?

Sorry for my bad English. Thank you

Upvotes: 4

Views: 54

Answers (3)

This
This

Reputation: 121

re-write your get_queryset() as follows,

def get_queryset(self):
        return Question.objects.filter(question__isnull=False,pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

Upvotes: 1

Anup Yadav
Anup Yadav

Reputation: 3005

return Question.objects.filter(question_set__isnull=False, pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

Upvotes: 1

Lomtrur
Lomtrur

Reputation: 1798

Choice.question_set.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

This uses following foreign key relations backwards, as described in the Django docs here.

Choice.question_set.all() is used to get all Question objects that do have a choice by following the relation backwards from Choice.

Upvotes: 0

Related Questions