python - Django 向后关系

标签 python django

我正在为应用程序设置网络服务,我有以下模型:

class Parent(models.Model):
    ...
class Child(models.Model):
    parent = models.ForeignKey(Course)
    ...

关系是一对多(1 个父级,多个子级)
现在,我想获取所有 Parent 对象及其特定的 Child 并将其作为 JSON 请求发送。是否可以这样做而不必首先获取所有“ child ”并迭代它们以寻找与特定父级相关的那些?
我认为这对于真正的大型数据库来说效率极低,而且“Childs”不会在其他“Parents”中重复

非常感谢

最佳答案

Django 中的每个关系都会自动将其反向关系添加到模型中。在 ForeignKey 的情况下或 ManyToManyField该关系包含多个对象。在这种情况下,默认属性名称设置为 <model>_set ,所以在这种情况下 child_set .这是一个管理器,可以这样使用,例如迭代所有 child :

for child in parent.child_set.all():
    do_something()

您还可以使用 related_name 指定用于反向关系的属性名称。属性:
class Child(models.Model):
    parent = models.ForeignKey(Parent, related_name='children')

for child in parent.children.filter(some_field=True):
    do_something()

following relations backwards 上的文档中阅读更多信息和 how are backward relationships possible .

关于python - Django 向后关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23046213/

相关文章:

python - 带有 NEAT 的 pygame 的 flappy bird 游戏中不显示管道

python - 在 Python 中分别洗牌两个列表

python - 正则表达式可以用作字典中的键吗?

django - Django 项目目录结构是否可以更简单,带或不带 South ?

django - 指定 Django 相关模型排序顺序

python - Django登录系统

python - 检测 2 个数据帧中的重叠值

python - django.db.utils.IntegrityError : duplicate key value violates unique constraint "auth_permission_pkey" 错误

python - 导入错误无法在windows环境下导入名称execute_manager

django - Django 上具有子域的多个 PostgreSQL 架构和用户