Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Find most common field value in queryset

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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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")
about 4 years ago · Santiago Trujillo Report

0

from django.db.models import Count

most_common = Post.objects.annotate(mc=Count('category')).order_by('-mc')[0].mc

You can find more information in the docs

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!