Django models filter by foreignkey

雨燕双飞 提交于 2019-11-30 11:56:08

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

in django 2 is ForeignKey.limit_choices_to docs

staff_member = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    limit_choices_to={'is_staff': True},
)
underbar
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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!