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
>>> 

>>>
>>>

2 comments:

  1. sir,
    agent=454200 what base u select value i means how can identity this value

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete