Reputation: 1432
I have a model called Post
which has two fields upvotes
and downvotes
. Now, upvotes
, downvotes
are ManyToManyField
to a User
. This is the model:
class Post(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
content = models.CharField(max_length=1000)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE)
upvotes = models.ManyToManyField(Profile, blank=True, related_name='upvoted_posts')
downvotes = models.ManyToManyField(Profile, blank=True, related_name='downvoted_posts')
I have to make a query where I have to get all posts sorted by
total (upvotes
) - total (downvotes
)
I have tried Post.objects.order_by(Count('upvotes'))
to get started but there's an error.
Upvotes: 2
Views: 52
Reputation: 23064
Use QuerySet.annotate() first.
Post.objects.annotate(
total_votes=Count('upvotes')-Count('downvotes')
).order_by('total_votes')
An added benefit of annotate()
is that every Post in the queryset gets the total_votes
attribute, which you can access later with no additional database query or calculation.
Upvotes: 2