【问题标题】:Can a parent class check if child class has such field?父类可以检查子类是否有这样的字段吗?
【发布时间】:2017-07-07 21:35:22
【问题描述】:

我知道我们可以从孩子那里引用父母的模型,但有没有其他方法可以让它使用?

抱歉这里有任何错别字。

假设父母是

class Parent(Model):
    has_this = models.Charfield(max_length=128)

class Child(Parent):
    has_that = models.Boolean(default=True)

ch = Child.objects.filter(id=1).first()  // this will be instance of both Parent and Child as expected

pa = Parent.objects.filter(id=1).first() // is actually return the same as above but does not has the `Child` field `has_that`

我的问题是,如果使用 Parent.objects.filter 调用查询,pa 是否可以与常规的 Parent 区别开来

我尝试使用isisntance,但对于pa,只有在Parentch 时才适用,两者都适用。我想不出另一种方法来区分这一点。

另外,Parent 不会是抽象的。

附:我想过使用hasattr,但这也行不通。

提前致谢。

【问题讨论】:

标签: django inheritance field instance


【解决方案1】:

您可以通过使用子类作为字段名称来引用子类属性:

Parent.objects.filter(child__isnull=True)

产生所有裸 Parent 实例(不是子实例)。

但是,当您有多个派生类时,这会有点笨拙。

显然,您也可以通过这种方式通过父类查询子字段:

Parent.objects.filter(child__has_that=True)

产生同样是ChildrenParent 实例,其中has_that 设置为True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-05
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多