gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:09:05 30 4
gpt4 key购买 nike

我有一个 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com