1

When annotating something to a model in Django one would write something like this:

Post.objects.all().annotate(total_yes_votes=Count('vote', filter=Q(vote__vote_choice='yes')))

What if I want to annotate on a single object and not all() the objects:

Post.objects.get(id=id).annotate(total_yes_votes=Count('vote', filter=Q(vote__vote_choice='yes')))

By the way, it doesn't work.

Isn't it more efficient to annotate a single object rather than all()?

1 Answer 1

2

Move the call to .get() to after the annotation

Post.objects.annotate(total_yes_votes=Count('vote', filter=Q(vote__vote_choice='yes'))).get(id=id)
Sign up to request clarification or add additional context in comments.

2 Comments

I get AttributeError: 'Post' object has not attribute annotate
@Steffi: That sounds like you're trying to do some_post.annotate, but you need to use .annotate on Post.objects, i.e. before the .get, not after.

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.