2015-04-16 31 views
2

我有一些Django模型繼承PolymorphicModel(從Django多態)。我想爲特定的模型類型創建一個GenericForeignKey關係,它是子模型。使用過濾器來限制GenericForeignKey模型列表與Django多態

喜歡的東西:

# application_one/models.py 

from django.db import models 
from polymorphic import PolymorphicModel 
from django.contrib.contenttypes.fields import GenericForeignKey 
from django.contrib.contenttypes.models import ContentType 

class ModelA(PolymorphicModel): 
    name = models.CharField(max_length=100) 

class ModelB(ModelA): 
    new_property = models.CharField(max_length=100) 

class ModelC(ModelA): 
    other_property = models.CharField(max_length=100) 

class OtherModel(models.Model): 
    pass 

class ModelWithRelation(models.Model): 
    # We want to limit the related_model to ModelA, or it's children 
    related_model = models.ForeignKey(ContentType) 
    object_id = models.IntegerField() 
    content_object = GenericForeignKey('related_model', 'object_id') 

--- ---和

# application_two/models.py 
from application_one.models import ModelA 

class ModelD(ModelA): 
    pass 

您可以通過在limit_choices_to明確指定型號名稱限制的ContentType的選擇,但其實我是想這是ModelA的子類的一個動態查詢,因爲在我們的應用程序中,我們期待ModelA的子類存在於其他應用程序中,並且不希望在application_one中定義它們。

我該如何去定義一個Q對象(或任何我需要做的),以便能夠在相關對象上設置limit_choices_to(即related_model = models.ForeignKey(ContentType))。

TIA!

回答

2

這是Django Polymorphic的一個內置功能,您不需要創建GenericForeignKey,只需創建一個定期的ForeinKeyModelA,Django Polymorphic將負責其餘的部分。

查看Django Polymorphic's documentation on ForeignKeys瞭解更多信息

+0

太棒了!我應該知道的! –

相關問題