So, I have a Post model which contains PostVotes from users
class Post(models.Model):
voters = models.ManyToManyField(User, through="PostVote")
#other stuff
and the post vote can have a state of either "upvote" or "downvote" (I know I should be using enums or a bool for this before I start receiving those comments) and in many cases I need to count the total score of the object for the frontend. When I have the posts in a queryset, the following solution is working well:
posts = Post.objects.all().annotate(vote=models.Sum(
models.Case(
models.When(postvote__state="upvote", then=1),
models.When(postvote__state="downvote", then=-1),
default=0,
output_field=models.IntegerField()
)
))
However, there are many cases where I want to do a similar thing but instead of a queryset I have just a single instance. How do I do this? Trying the above solution gives 'Post' object has no attribute 'annotate'