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

107
Vistas
Get number of filtered items with a backward reference to a model Django

I have being playing with this for hours with out find a solution.

I have the following models:

class Category(models.Model):
    name = models.CharField(max_length=100)

class Item(models.Model):
    name = models.CharField(max_length=250)
    category = models.ForeignKey(Category)

Then I filter the Items and the categories related to that item:

items = Item.objects.filter(name=name)
categories = Category.filter(id__in = items.values_list('category__id'))

Now I want to get the number of the items with a category and save that number in a field in categories with annotate

How can I do it?

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

0

Try the following code

from django.db.models import Count

items = Item.objects.filter(name=name)
categories = Category.objects.filter(
    id__in=items.values_list('category_id')
).annotate(items_count=Count("item"))

for cat in categories:
    print cat.name, cat.items_count

for reference: https://docs.djangoproject.com/en/1.11/topics/db/aggregation/

over 4 years ago · Santiago Trujillo Denunciar

0

Then I filter the Items and the categories related to that item.

If each item can point to several categories, I think you need ManyToMany field.

Now I want to get the number of the items with a category

category = Category.objects.filter(name=name)
num_items = Item.objects.filter(category=category).count()
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