【问题标题】:How to count all ForeignKey models with exact field values in Django?如何计算 Django 中具有精确字段值的所有 ForeignKey 模型?
【发布时间】:2016-01-14 08:02:04
【问题描述】:

我不确定这是否可能,但我想计算与具有确切 vote_type 属性的模型相关的所有投票。

这是模型:

class Link(models.Model):
    title       = models.CharField(max_length=200)
    . . . 

class Vote(models.Model):
    UP, DOWN = range(2)
    TYPE_CHOICES = [(UP, "Upvote"), (DOWN, "DownVote")]

    link = models.ForeignKey(Link, related_name='votes')
    vote_type = models.IntegerField(choices=TYPE_CHOICES, db_index=True)
    . . . 

我用它来统计所有选票:

Link.objects.annotate(ups=Count('votes')).order_by('-ups')

我想也许我可以用它来实现我想要的:

Link.objects.annotate(ups=Count('votes__vote_type__exact=1')).order_by('-ups')

但我似乎不能在这里使用 filter() 语法。

我正在使用 Django 1.8.4。

【问题讨论】:

    标签: python django django-queryset django-database django-aggregation


    【解决方案1】:

    您可以在执行注释之前根据类型过滤投票。

    Link.objects.filter(votes__vote_type=1).annotate(ups=Count('votes')).order_by('-ups')
    

    来源:https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#order-of-annotate-and-filter-clauses

    【讨论】:

      猜你喜欢
      • 2010-11-08
      • 2018-03-16
      • 2018-07-14
      • 2020-06-06
      • 1970-01-01
      • 2017-12-15
      • 2020-08-06
      • 1970-01-01
      • 2019-12-27
      相关资源
      最近更新 更多