【问题标题】:How to count the number of unique values on query's related model in Django?如何计算 Django 中查询相关模型中唯一值的数量?
【发布时间】:2021-08-21 04:54:58
【问题描述】:

假设我有这三个模型:

class User(models.Model):
    ....

class Tweet(models.Model):
    created_at = models.DateTimeField(blank=True, null=True)
    user = models.ForeignKey(
        "core.User", related_name="tweets", on_delete=models.SET_NULL, null=True
    )


class Tag(models.Model):
    tag = models.CharField(max_length=100, blank=False, unique=True)
    tweets = models.ManyToManyField(Tweet, related_name="calls")

我要构建的查询是“标签,按在特定时间段内发布推文的唯一推文用户的数量排序”。我已经构建了一个自定义计数查询来实现这一点,它有效,但速度很慢。我现在已经按照上面的方式安排了 DB,标签作为与 Tweets 相关的单独模型。

tags = Tag.objects.filter(tweets__created_at__week=date.isocalendar()[1]).annotate(count=Count('tweets__user')).filter(count__gt=1).order_by('-count', 'asset').distinct()

问题是,查询的Count('tweets__user') 部分有效地计算了与标签关联的推文数量。推文可以(并且)通常来自同一个帐户,我想要唯一的推特用户帐户的数量。有没有办法构建这个查询,用这种方式建模的数据,只使用 Django?

【问题讨论】:

    标签: sql django django-queryset


    【解决方案1】:

    Count('tweets__user') 部分查询有效地计算 与标签关联的推文数量。

    发生这种情况是因为tweets 是一个 m2m 并且编写该部分会构成一个连接,因此会计算所有推文。要解决这个问题,您需要在调用 Count [Django docs] 时指定 distinct 关键字参数:

    tags = Tag.objects.filter(
        tweets__created_at__week=date.isocalendar()[1]
    ).annotate(
        count=Count('tweets__user', distinct=True)
    ).filter(count__gt=1).order_by('-count', 'asset').distinct()
    
    

    【讨论】:

      猜你喜欢
      • 2018-09-13
      • 1970-01-01
      • 2018-08-25
      • 2018-09-10
      • 2018-02-20
      • 2020-05-19
      • 2018-04-03
      • 2021-12-17
      • 1970-01-01
      相关资源
      最近更新 更多