How can I filter model objects so their foriegn keys are not empty in django?

I have 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 only the last 5 questions that have a choice. In other words, questions are not returned without any choice. my opinion:

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 be applied to the return statement?

Sorry for my bad english. Thanks you

+4
source share
3 answers
return Question.objects.filter(question_set__isnull=False, pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
+1
source

rewrite 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]
+1
source
Choice.question_set.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

, Django .

Choice.question_set.all() Question, , Choice.

0

Source: https://habr.com/ru/post/1693358/


All Articles