Home > Software engineering >  Django generic.ListView: do not display Questions that have no specified Choices
Django generic.ListView: do not display Questions that have no specified Choices

Time:10-17

The models are:

class Question(models.Model):
    question_text = models.CharField(max_length=200)

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

Some Questions have no Choices specified by the admin. I don't want to display such Questions.

If the solution is to override get_queryset, then how to do that? Or is it better to get all Questions (Question.objects.all()) and to filter them in the view?

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

    def get_queryset(self):
        # How?

CodePudding user response:

You can either set the queryset attribute on the View

class QuestionList(generic.ListView):
    model = Question
    queryset = Question.objects.filter(choice__isnull=False).distinct()

Or override get_queryset

class QuestionList(generic.ListView):
    model = Question

    def get_queryset(self):
        return super().get_queryset().filter(choice__isnull=False).distinct()
  • Related