2017-07-07 56 views
0

我知道我們可以從孩子中引用父母的模型,但有沒有辦法以其他方式擁有?父類可以檢查子類是否有這樣的字段?

對不起,這裏有任何錯字。

比方說,如果父母是

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` 

我的問題是什麼,是有pa的方式從常規Parent差動如果查詢使用Parent.objects.filter

我嘗試使用isisntance但對於所謂的pa,只有在Parentch這兩種情況都是如此。我想不出另一種方式來區分這一點。

另外,Parent不會是抽象的。

P.S.我想過使用hasattr,但這不起作用。

在此先感謝。

+0

聲音就像你想要的[Django模型繼承 - 只需要在查詢中父類的實例](https://stackoverflow.com/questions/11853850/django-model-inheritance-only-want-instances-of-parent -class功能於一個查詢) – dhke

回答

1

您可以使用子類的字段名稱引用子屬性:

Parent.objects.filter(child__isnull=True) 

產生的所有裸Parent實例(兒都沒有)。

但是,當您有多個派生類時,這會稍微不便。

當然,你還可以通過父類查詢子領域是這樣的:

Parent.objects.filter(child__has_that=True) 

產生,同時也是Childrenhas_that設置爲TrueParent實例。

相關問題