简体   繁体   English

如何查询集继承模型django?

[英]How to queryset inheritance model django?

I have models我有模特

class Parent(Model):
    pass

class Child1(Parent):
    att1 = CharField()

class Child2(Parent):
    att2 = CharField()

class Final(Model):
    parent = ForeignKey('Parent', related_name="final")

I need to queryset我需要查询集

Final.objects.filter(parent__att1='abc')

But just Child1 inheritance Parent has att1 .但只是Child1继承Parentatt1 How to queryset att1 in Child1 not Child2 ?如何查询集ATT1Child1CHILD2?

You can query with:您可以查询:

Final.objects.filter(parent__child1__att1='abc')

In Django model inheritance (of non-abstract models) is achieved by adding an implicit OneToOneField in the child model(s).在 Django 模型继承(非抽象模型)是通过在子模型中添加一个隐式OneToOneField来实现的。 We can thus use that relation by querying in reverse .因此,我们可以通过反向查询来使用该关系。

This will thus create a query that looks like:因此,这将创建一个如下所示的查询:

SELECT final.*
FROM final
INNER JOIN parent ON final.parent_id = parent.id
INNER JOIN child1 ON parent.id = child1.parent_ptr_id
WHERE child1.att1 = 'abc'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM