Django models filter by foreignkey Django models filter by foreignkey django django

Django models filter by foreignkey


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')


in django 2 is ForeignKey.limit_choices_to docs

staff_member = models.ForeignKey(    User,    on_delete=models.CASCADE,    limit_choices_to={'is_staff': True},)


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.