Custom Search

Tuesday, March 10, 2015

How to Django Aggregate with Distinct

1)
Open Django shell
#python manage.py shell

2)
>>>
>>>
>>> from django.db.models import Count
>>> from bla.core.models import Building
>>>
>>> Building.objects.filter(agent=454200).aggregate(count=Count('user'))
{'count': 29}
>>>

>>>
>>> Building.objects.filter(agent=454200).aggregate(count=Count('user', distinct=True))
{'count': 7}
>>>

>>>
>>>
>>>
>>> user_tot = 0
>>> for b in Building.objects.filter(agent=454200).all():
...     if b.user:
...         user_tot += 1
...
>>>
>>>

>>> user_tot
29
>>> 

>>>
>>>

No comments:

Post a Comment