python - How to count a field and this same field but filtered, in one query in Django? -
i'm not web developper sorry title of question doesn't make sense.
to make things easier, here models (i stripped non necessary fields demonstration):
class user(models.model): username = models.charfield(max_length=100) class vote(models.model): user = models.foreignkey(askfmuser) date = models.datetimefield('vote date')
and in view, need list users, number of votes received, ordered votes. have no problem doing this, query :
global_votecount = vote.objects.all().values('user', 'user__username').annotate(votestotal=count('user__username')).order_by('-votestotal')
and in template, display on table 2 columns (username, , vote count).
but need do, display total vote count received time, also, in same html table, name of votes received today.
i know can votes today query:
now = timezone.now() today_votecount = vote.objects.filter(date__year=now.year, date__month=now.month, date__day=now.day).values('user', 'user__username').annotate(todayvotescount=count('user__username'))
but problem if no votes made specific user during day, not appear in list. also, list, if ordered order_by, ordered differently.
so... see "clean" solution able total vote count , vote count timeperiod (by filtering in "date" field), in single query ? if not possible... manually go though these 2 valuesqueryset add field in first 1 (corresponding "today votes count", when username found in second 1 ?
thank you
i'm not sure how in 1 query, consider this:
global_votecount = vote.objects.all().values('user', 'user__username').annotate(votestotal=count('user__username')).order_by('-votestotal') import datetime today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min) today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max) votestoday = dict(vote.objects.filter(date__range=(today_min, today_max)).values_list('user__username').annotate(votestoday=count('user__username'))) item in global_votecount: item['votestoday'] = votestoday[item['user__username']]
this uses 2 queries, , takes results of second , applies results of first query.
Comments
Post a Comment