24

I'm having some trouble in filtering objects from a set of models. Here is the problem:

I have 3 classes:

class Autor(models.Model):    
    nome = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, blank=True, unique=True)
    foto = models.ImageField(upload_to='autores/', null=True, blank=True)
    ...

class CategoriaRecolha(models.Model):
    categoria = models.CharField(max_length=30)
    descricao = models.TextField()
    slug = models.SlugField(max_length=30, blank=True, unique=True)
    ...

class Recolha(models.Model):    
    titulo = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, blank=True, unique=True)
    descricao = models.TextField()
    ficha_tec = models.TextField()
    categoria = models.ForeignKey(CategoriaRecolha)
    autor = models.ForeignKey(Autor)
    ....

What I'm trying to retrieve is the fields of the class Autor, in which the field categoria of the class Recolha is equal to a specific value.

In a more simple way, I need to get the all the autor that have participated in a specific categoria.

Thanks

Will
  • 11,276
  • 9
  • 68
  • 76
maloky
  • 343
  • 1
  • 2
  • 6

3 Answers3

35

A more direct alternative:

autors = Autor.objects.filter(recolha__categoria=MyCategoria)

where MyCategoria is the relevant CategoriaRecolha instance. Or, if you want to match agains the specific category name, you can extend the query another level:

autors = Autor.objects.filter(recolha__categoria__categoria='my_category_name')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
23

in django 2 is ForeignKey.limit_choices_to docs

staff_member = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    limit_choices_to={'is_staff': True},
)
clemens
  • 16,716
  • 11
  • 50
  • 65
sVs
  • 231
  • 2
  • 2
5
cat = CategoriaRecolha.objects.get(field=value)
rows = Recolha.filter(categoria=cat)
autors = [row.autor for row in rows]

The Django Docs explain this pretty well.

Tony
  • 9,672
  • 3
  • 47
  • 75
underbar
  • 588
  • 3
  • 15