【问题标题】:Django backwards relationDjango 反向关系
【发布时间】:2014-05-27 14:14:54
【问题描述】:

我正在为应用程序设置 Web 服务,并且我有以下模型:

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

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

非常感谢

【问题讨论】:

    标签: python django


    【解决方案1】:

    Django 中的每个关系都会自动将其反向关系添加到模型中。对于ForeignKeyManyToManyField,该关系包含多个对象。在这种情况下,默认属性名称设置为<model>_set,因此在这种情况下为child_set。这是一个经理,可以这样使用,例如遍历所有孩子:

    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 backwardshow are backward relationships possible 的文档中了解更多信息。

    【讨论】:

    • 谢谢,这真的很有用。
    【解决方案2】:

    为什么需要迭代?即使 Django 没有为您提供特殊的向后语法,您也可以随时这样做:

    Child.objects.filter(parent=my_parent)
    

    但是作为粗略的谷歌你的问题的标题会显示,向后关系有一种特殊的语法:

    my_parent.child_set.all()
    

    【讨论】:

      【解决方案3】:

      是的,在 django 中你可以使用:

      parentInstance.child_set.all()
      

      其中parentInstanceParent 数据库中的一个特定父级。这将以有效的方式返回与其关联的所有子对象。要使其成为 JSON 响应,您可以尝试以下操作:

      import json
      
      from django.http import HttpResponse
      
      response_data = {}
      response_data[str(parentInstance)] = parentInstance.child_set.all()
      return HttpResponse(json.dumps(response_data), content_type="application/json"
      

      采用自here

      【讨论】:

        猜你喜欢
        • 2018-07-05
        • 2010-11-03
        • 2013-10-20
        • 2012-12-25
        • 1970-01-01
        • 2017-05-31
        • 2013-06-24
        • 2011-12-27
        • 2020-03-24
        相关资源
        最近更新 更多