我有一个 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
我该如何做到这一点?
annotate
实现此功能。您只需将 "designation" 更改为 "category" 即可。 - FamousJameous