0

Filter and Count User was Joined by Date Joined. This qustion hasbeen asked with someone in https://www.facebook.com/groups/DjangoID/permalink/1269996159681000/, he asked, “How to grouping and count data by date_joined from User models? and then end result of it is like this, -> “

[{'date': '2015-12-30', 'total': 5}, {'date': '2016-01-01', 'total': 3}, {'date': '2016-01-02', 'total': 13}]

And this is answer of it in my opinion to solved it:

>>> from django.contrib.auth.models import User
>>> usr = User.objects.all().order_by('-date_joined')
>>> usr
[<User: gahashe21>, <User: gahashe>, <User: pqsmedia>, <User: summon>, <User: agus>, <User: agaust>]
>>>
>>> [ u.date_joined for u in usr ]
[datetime.datetime(2015, 12, 29, 16, 50, 22, 57298, tzinfo=<UTC>), datetime.datetime(2015, 12, 29, 16, 48, 37, tzinfo=<UTC>), datetime.datetime(2015, 12, 26, 11, 35, 55, 307318, tzinfo=<UTC>), datetime.datetime(2015, 12, 18, 16, 6, 22, tzinfo=<UTC>), datetime.datetime(2015, 12, 15, 11, 7, 24, tzinfo=<UTC>), datetime.datetime(2015, 12, 14, 7, 3, 43, tzinfo=<UTC>)]
>>> 
>>> usr[0].date_joined.date()
datetime.date(2015, 12, 29)
>>> 
>>> from django.db.models import Count
>>> User.objects.filter(pk__in=usr).values('date_joined').annotate(total=Count('pk'))
[{'total': 1, 'date_joined': datetime.datetime(2015, 12, 14, 7, 3, 43, tzinfo=<UTC>)}, {'total': 1, 'date_joined': datetime.datetime(2015, 12, 15, 11, 7, 24, tzinfo=<UTC>)}, {'total': 1, 'date_joined': datetime.datetime(2015, 12, 18, 16, 6, 22, tzinfo=<UTC>)}, {'total': 1, 'date_joined': datetime.datetime(2015, 12, 26, 11, 35, 55, 307318, tzinfo=<UTC>)}, {'total': 1, 'date_joined': datetime.datetime(2015, 12, 29, 16, 48, 37, tzinfo=<UTC>)}, {'total': 1, 'date_joined': datetime.datetime(2015, 12, 29, 16, 50, 22, 57298, tzinfo=<UTC>)}]
>>> 
>>> User.objects.filter(pk__in=usr).extra({'date_joined': 'date(date_joined)'}).values('date_joined').annotate(total=Count('pk'))
[{'total': 1, 'date_joined': u'2015-12-14'}, {'total': 1, 'date_joined': u'2015-12-15'}, {'total': 1, 'date_joined': u'2015-12-18'}, {'total': 1, 'date_joined': u'2015-12-26'}, {'total': 2, 'date_joined': u'2015-12-29'}]
>>> 
>>> 

Refference:

problem python django

Your Answer

blog comments powered by Disqus