Skip to main content
 首页 » 编程设计

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

2025年02月15日7findumars

我有一个 Post 和 Profile 模型。我试图在用户帖子列表中找出最常见的 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 

我该怎么做?

请您参考如下方法:

您可以使用原始查询来完成。在原始查询表中必须是您给类 Meta 的名称:或保存在数据库 shema 中的表名。

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