Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
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?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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

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

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda