Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda