Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Queryset Count

My model:

class Device(models.Model):
    build = models.CharField()
    name = models.CharField()

How do I build my queryset so I can get the count of objects with different builds.

For example if there were two builds 'build 1' and 'build 2', I would want an output that would tell me

build 1 = 3
build 2 = 4

EDIT: Tried the following:

Device.objects.values('build').annotate(count=Count('pk'))

the output is:

[{'build': u'wed build'}, {'build': u'red build'}, ... ]
like image 761
ellieinphilly Avatar asked Jan 28 '26 15:01

ellieinphilly


1 Answers

from django.db.models import Count

Device.objects.values('build').annotate(count=Count('pk'))
# -> [{'build': '1', 'count': 3}, {'build': '2', 'count': 4}]
like image 138
Pavel Anossov Avatar answered Jan 30 '26 04:01

Pavel Anossov