[Django]-Django models filter by foreignkey

36๐Ÿ‘

โœ…

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

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},
)
๐Ÿ‘คsVs

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.

๐Ÿ‘คunderbar

Leave a comment