【问题标题】:How to count a field and this same field but filtered, in one query in Django?如何在 Django 的一个查询中计算一个字段和同一个字段但已过滤?
【发布时间】:2015-03-20 22:30:29
【问题描述】:

我真的不是网络开发人员,很抱歉我的问题标题没有真正意义。

为了让事情更简单,这是我的模型的样子(我为演示去掉了不必要的字段):

class User(models.Model):
    username = models.CharField(max_length=100)
class Vote(models.Model):
    user = models.ForeignKey(AskFmUser)
    date = models.DateTimeField('vote date')

在一个视图中,我需要列出所有用户,以及他们收到的票数,按票数排序。使用这个查询我没有问题:

global_votecount = Vote.objects.all().values('user', 'user__username').annotate(votesTotal=Count('user__username')).order_by('-votesTotal')

在我的模板中,我将它显示在一个包含两列(用户名和投票数)的表格上。

但我需要做的是显示他们一直以来收到的总票数,而且,在同一个 HTML 表格中,他们今天收到的票的名称。

我知道我可以通过以下查询为今天投票:

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

但问题是,如果白天没有为特定用户投票,他就不会出现在列表中。此外,即使使用 order_by 排序,列表也会以不同的方式排序。

所以...您是否看到任何“干净”的解决方案能够在单个查询中获得总投票数和一段时间内的投票数(通过在“日期”字段中过滤)? 如果不可能...我可以手动通过这两个 ValuesQuerySet 在第一个中添加一个字段(对应于“今天的投票计数”,当在第二个中找到用户名时?

谢谢

【问题讨论】:

    标签: python django


    【解决方案1】:

    我不确定如何在一个查询中执行此操作,但请考虑以下内容:

    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')))
    
    
    for item in global_votecount:
        item['votesToday'] = votesToday[item['user__username']]
    

    这使用两个查询,并获取第二个查询的结果并将其应用于第一个查询的结果。

    【讨论】:

    • 感谢您的回答。是的,我想我将不得不使用两个查询并通过 python 中的 ValuesQuerySet。它会增加一些服务器负载,但是......我想我无法避免它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多