代码之家  ›  专栏  ›  技术社区  ›  jul

我如何知道模型的实例是由子模型的实例创建的?

  •  2
  • jul  · 技术社区  · 15 年前

    我有一个从(非抽象)模型父代继承的模型子代。 对于给定的父级实例,我如何知道它是否是子级?

    如果是,

    parent.child
    

    返回子级,否则返回doesnotex异常。

    是唯一的检查方法吗?

    谢谢

    7月

    编辑编辑

    我在这里找到了同样的问题: Distinguishing parent model's children with Django inheritance .

    答案是……

    hasattr(parent, 'child')
    
    3 回复  |  直到 15 年前
        1
  •  0
  •   Pi Delport    15 年前

    是唯一的检查方法吗?

    或多或少。

    如果你只想要一个存在检查,你可以通过说 Child.objects.filter(parent=parent).exists() 但是如果你想和孩子做点什么,如果它存在的话,最好直接访问它并处理 DoesNotExist .

        2
  •  0
  •   Community Mohan Dere    9 年前

    我在这里找到了同样的问题: Distinguishing parent model's children with Django inheritance .

    答案是……

    hasattr(parent, 'child')
    
        3
  •  -2
  •   Ned Batchelder    15 年前

    你可以使用 instanceof(parent, Child) . 子实例返回true,父实例返回false。