如何计算 Django 中查询相关模型的唯一值数量?

How to count the number of unique values on query's related model in Django?

假设我有这三个模型:

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

我要构建的查询是 'Tags, ordered by the number of unique tweet users which made tweets in a particular time period'。我已经构建了一个自定义计数查询来实现这一点,它有效,但速度很慢。我现在已经按照上面的方式安排了数据库,标签作为与推文相关的单独模型。

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') 部分有效地计算了与标签关联的推文数量。这些推文可以(并且经常)来自同一个帐户,我想要唯一的 Twitter 用户帐户的数量。有没有一种方法可以仅使用 Django 构建此查询,并以这种方式建模数据?

Count('tweets__user') part of the query effectively counts the number of tweets associated with the tag.

发生这种情况是因为 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()