在查询集中找到最常见的字段值

4

我有一个 PostProfile 模型。我正在尝试找出用户帖子列表中最常见的 category

以下是我的模型:

class Post(models.Model):
    user = models.ForeignKey(User, blank=True, null=True)
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1')

class Profile(models.Model):
    user = models.ForeignKey(User, blank=True, null=True)

    def most_common_category(self):
        posts = Post.objects.filter(user=self.user)
        for post in posts:
            print(post.category) # 1, 1, 2, 3, 2, 2, 4, 1, 2, 2

我该如何做到这一点?

请参考 https://dev59.com/fHRB5IYBdhLWcg3wa2q2#629691 上的方法,使用 annotate 实现此功能。您只需将 "designation" 更改为 "category" 即可。 - FamousJameous
2个回答

5

您可以通过使用原始查询来实现。在原始查询中,表必须是您在class Meta:中指定的名称或保存在数据库模式中的表名。

most_common = Post.objects.raw(select 1 as id, category, count(category) from post group by category order by count(category) desc)

或者您可以使用.values
most_common = Post.objects.values("category").annotate(count=Count('category')).order_by("-count")

请注意:Post.objects.raw(...) 中的所有内容都应该是一个字符串。因此应该是 Post.objects.raw('select 1 as id, category, count(category) from post group by category order by count(category) desc') - Joshua Swain

0
from django.db.models import Count

most_common = Post.objects.annotate(mc=Count('category')).order_by('-mc')[0].mc

您可以在文档中找到更多信息。


刚试了一下,它没有按最常见的类别排序。编辑:现在它可以了,谢谢。 - Zorgan
我已经尝试了更多的帖子将类别2而不是类别1,但它仍然说类别1是最常见的。这似乎只打印查询集中的第一个类别。 - Zorgan
您可以使用以下代码按照最常见的顺序检查所有类别:Post.objects.annotate(mc=Count('category')).order_by('-mc') - Danil
它没有按照最常见的顺序显示类别,而是只是遍历它们(1, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2,)。 - Zorgan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接