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

标签 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

我该怎么做?

最佳答案

您可以使用原始查询来完成。在原始查询表中必须是您给类 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")

关于python - 在查询集中查找最常见的字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43552830/

相关文章:

python - 使用 Python 的 ElementTree 合并 XML 文件并维护 CDATA 标签

django - 关于Django中批量保存对象的问题

javascript - 用javascript或python镜像的html

Django celery ubuntu 14.04

python - 用Python读取CSV文件

python - 尝试学习 F#...对整数列表进行排序

python - 计算数据结构的 md5 哈希

python - 与 python 中每个确切位置的列表进行比较

django - 在 Django 项目中,python 类的最佳位置是什么?

python - django 在 Raspberry PI 中使用热敏打印机