I have a Post and Profile model. I'm trying to find out the most common category in a list of user posts.
Here's my models:
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
How would I do this?
you can do it by using raw query. In raw query table must be the name that you given class Meta: or table name saved in database shema.
most_common = Post.objects.raw(select 1 as id, category, count(category) from post group by category order by count(category) desc)
or you can use .values.
most_common = Post.objects.values("category").annotate(count=Count('category')).order_by("-count")