Django count records with aggregate

Question:

I have field like this:

Showing field value

I want all records count with all tags for example

sale = Sale.objects.using('read_rep') 
        .filter(tags__name__in=['Device','Mobile']) 
        .aggregate(
         **{total: Count('pk', for status, _ in ['Device','Mobile']}
 )


Device - 2 Mobile-5

It is difficult to count records with all tags because tags are being store in only one field.

Asked By: patel887

||

Answers:

Try values and annotate approach.

sale = Sale.objects.using('read_rep') 
        .filter(tags__name__in=['Device','Mobile']).values(
                'tags__name'
            ).annotate(
                tags_count=Count('tags__name')
            )

Which gives:

[
    {'tags__name': "Device", 'tags_count': 3},
    {'tags__name': "Mobile", 'tags_count': 5},
]
Answered By: Sergey Pugach