2

I'm new to django so this must be a silly question but i was working my way through the official documentation tutorial(the one about a site with polls and choices) and i wanted to filter out polls with no choices, i managed to do that with a filter in the queryset argument of the ListView:

queryset=Poll.objects.filter(pub_date__lte=timezone.now).filter(id__in=Choice.objects.all).order_by('-pub_date')[:5]

And this indeed filters the query, the problem is that if i add a choice to a poll that didn't have any choices from the admin site, this won't be reflected on the site until i restart the server or i change some code in the project, even though i'm passing a callable object as argument to the filter (which is the same as the previous filter in that same line), i searched in the rest of documentation and i also looked at the definitive guide to django but i found nothing, that could help me, so i don't really know if there's something wrong with the code, or i'm lacking some understanding of django or a particular concept of python itself

1
  • doesn't that query create a sql subquery which tested if the ids are in the choice table by using a join between polls and choices? Commented Jul 10, 2013 at 18:49

1 Answer 1

1

Your current query is incorrect because, You are filtering poll ids, if choice objects of the same ids are present in the database, which is not accurate.

To filter out polls with no choice, you need to do

queryset=Poll.objects.filter(choice__isnull=False).order_by('-pub_date').distinct()[:5] #Get only polls with a choice. 

Now,every Poll before now can be filtered like this:

queryset = Poll.objects.filter(choice__isnull=False, pub_date__lte=timezone.now()).order_by('-pub_date').distinct()[:5]
Sign up to request clarification or add additional context in comments.

6 Comments

okay, but does that solve the problem of not having to restart the server after i make a change from the admin site?
That issue should never have been there in the first place. Not sure why that is happening
karthikr I wrote the second line of code you posted but now a poll is displayed once for each choice it has and timezone.now is only computed the first time the server is run (this second fact appears in the tutorial
what part of the tutorial are you following ? The query retrives all the Polls which have choices associated with them
i finished all 5 parts of the tutorial, for some reason when i write your query (and that's the only modification i did) and access the page it displays every poll once for each choice it has, of course polls with no choices are filtered out, but that repetition is not needed
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.