Skip to content Skip to sidebar Skip to footer

Strange Behaviour For Annotate In Django

I have two database tables which are the following: class Story(models.Model): user = models.ForeignKey(User) date_added = models.DateTimeField(auto_now_add=True) date_

Solution 1:

Your model structure is confusing. It seems like you have a single StoryVote instance for each Story, and the StoryVote's vote field gets incremented each time. That is an usual structure: you would normally either keep the vote count on the Story itself, or just add a new StoryVote instance for each vote, so there would be no need for the vote count field. In your case, if you really do want to keep the models separate for reasons of your own, you should probably be using a OneToOneField rather than a foreign key.

Anyway, what your annotation is doing is counting the number of StoryVote instances for each Story: but as you note, that is always 1. But in your case there is no reason to use annotation, because there is just a single StoryVote: you can access the value directly:

most_voted = Story.objects.prefetch_related().order_by('-storyvote__votes')
for story in most_voted:
    print story.title + " has " + str(story.votes[0].votes) + " votes."

This would be even easier if you take my advice and used a OneToOne field:

most_voted = Story.objects.select_related().order_by('-storyvote__votes')
for story in most_voted:    
    print story.title + " has " + str(story.votes.votes) + " votes."

Post a Comment for "Strange Behaviour For Annotate In Django"