Why .filter() in django returns duplicated objects?

后端 未结 3 599
悲&欢浪女
悲&欢浪女 2021-01-17 12:03

I\'ve followed django tutorial and arrived at tutorial05.

I tried to not show empty poll as tutorial says, so I added filter condition like this:

cla         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-17 12:42

    A little late to the party, but I figured it could help others looking up the same issue. Instead of using choice__isnull=False with the filter() method, use it with exclude() instead to exclude out any questions without any choices. So your code would look something like this:

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

    By doing it this way, it will return only one instance of the question. Be sure to use choice_isnull=True though.

提交回复
热议问题