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

Zor*_*gan 3 python django

我有一个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
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Tha*_*eem 5

你可以通过使用原始查询来做到这一点。在原始查询表中必须是您指定的类 Meta: 或保存在数据库 shema 中的表名。

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

或者你可以使用.values.

most_common = Post.objects.values("category").annotate(count=Count('category')).order_by("-count")
Run Code Online (Sandbox Code Playgroud)