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:
class IndexView(generic.ListView):
...
def get_queryset(self):
return Question.objects.filter(
pub_date__lte=timezone.now(),
choice__isnull=False
).order_by('-pub_date')[:5]
But this returned two objects which are exactly same.
I think choice__isnull=False caused the problem, but not sure.
choice__isnull
causes the problem. It leads to join withchoice
table (to weed outquestions
withoutchoices
), that is something like this:You can inspect
query
attribute ofQuerySet
to be sure. So if you have onequestion
with twochoices
, you will get thatquestion
two times. You need to usedistinct()
method in this case:queryset.distinct()
.Because you created two objects with same properties. If you want to ensure uniqueness, you should add validation in
clean
and add unique index on identifier field too.Besides
filter
returns all the objects that match the criteria, if you are expecting only one item to be returned, you should useget
instead.get
would raise exception if less or more than 1 item is found.