python - Django ManyToMany 从列表中间接查找

标签 python django

我正在努力解决的愚蠢的简单问题:

我有两个模型,父模型和子模型

class Parent(models.Model):
    children = models.ManyToManyField(Child)

我有一个来自另一个查询的父模型列表,并且希望在单个查询中获取这些父模型的所有子模型,例如:

children = Child.objects.filter(parent_set__contains=list_of_parents)

我知道上面的内容是不对的,但我正在努力将 ORM 查询放在一起。甚至不确定如果不将一些 Q() 组合在一起是否可行?

我刚刚开始深入研究 ORM 过去的基本内容。

提前致谢!

最佳答案

使用in过滤器中的查找和parent(模型的小写名称):

children = Child.objects.filter(parent__in=list_of_parents)

关于python - Django ManyToMany 从列表中间接查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812980/

相关文章:

python - VPS 服务器上的 Pygame.display.init() 错误 : "No available video device",

python - 通过 Mutagen 在 Python 中确定 MP3 位深度

python - 具有 ManyToManyField 的模型

python - 没有外键的 Django 中的 Span 模型

python - Django 重复条目 1062

python - 复制字符串 - Python

python - Django 下拉过滤器与ajax?

javascript - Django 模板中的 Vue.js

python - Django - 使用从类似 REST 的 API 检索的数据构建报告的应用程序

python - 如何替换/删除 PySpark RDD 中的正则表达式?