0

I have confusion in result of these queries:

>>> [f.count for f in Favourite.objects.annotate(count = Count('object_id'))]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

and second one is

>>> [f['count'] for f in Favourite.objects.values('object_id').annotate(count=Count('object_id'))]
[1, 5, 2, 1, 4, 2, 2, 3]

but according to django docs first query should work fine, and Favourite object have count of object_id.

Can anyone explain why the second query is working, but not the first?

Thanks!

1 Answer 1

4

The second one is doing a group by on object_id. This is the expected behaviour. The first one is simply counting object_id for each row in the database.

Sign up to request clarification or add additional context in comments.

2 Comments

@Ahsan: The example you refer to in the docs uses annotation on a ManyToManyField so you can get counts > 1 for a single record, without grouping. For "normal" fields which are actual columns in the db table, you can obviously have just a count of 1 value per row without grouping by something.
@Béres Botond: I have also tried same as docs >>> [ge.c for ge in Album.objects.annotate(c=Count('genre'))] output: [1, 1, 1, 1, 1, 1, 1, 1] here genre have ManyToManyField relationshis with Album. And it works when i did >>> [ge['c'] for ge in Album.objects.values('genre').annotate(c=Count('genre'))] output: [1, 6, 1]

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.