2015-05-28 170 views
0

有了根據這種結構:Django的繼承和子類屬性

class A (models.Model): 
    common_attribute = models.IntegerField() 

class B (A): 
    subclass_attribute = models.IntegerField() 

class C (models.Model) 
    a = ForeignKey(A) 

...如果C的實例包含B的情況下,Django的似乎把這個作爲一個實例,我可以」訪問casubclass_attribute。有沒有解決的辦法?由於ForeignKeys的困難,我不想使用抽象繼承 - 我希望C支持A的任何子類。

回答

1

您可以通過使用django-polymorphic規避ForeignKey的困難。

Django的多態允許您查詢的基類對象,但檢索子類的實例:

>>> Project.objects.create(topic="Department Party") 
>>> ArtProject.objects.create(topic="Painting with Tim", artist="T. Turner") 
>>> ResearchProject.objects.create(topic="Swallow Aerodynamics", supervisor="Dr. Winter") 

>>> Project.objects.all() 
[ <Project:   id 1, topic "Department Party">, 
    <ArtProject:  id 2, topic "Painting with Tim", artist "T. Turner">, 
    <ResearchProject: id 3, topic "Swallow Aerodynamics", supervisor "Dr. Winter"> ] 

使用Django多態性你只需要使用多態模型作爲基類來聲明型號:

from django.db import models 
from polymorphic import PolymorphicModel 

class ModelA(PolymorphicModel): 
    field1 = models.CharField(max_length=10) 

class ModelB(ModelA): 
    field2 = models.CharField(max_length=10) 

class ModelC(ModelB): 
    field3 = models.CharField(max_length=10) 

外鍵也將返回子類實例,我認爲這正是你想要的。

# The model holding the relation may be any kind of model, polymorphic or not 
class RelatingModel(models.Model): 
    many2many = models.ManyToManyField('ModelA') # ManyToMany relation to a polymorphic model 

>>> o=RelatingModel.objects.create() 
>>> o.many2many.add(ModelA.objects.get(id=1)) 
>>> o.many2many.add(ModelB.objects.get(id=2)) 
>>> o.many2many.add(ModelC.objects.get(id=3)) 

>>> o.many2many.all() 
[ <ModelA: id 1, field1 (CharField)>, 
    <ModelB: id 2, field1 (CharField), field2 (CharField)>, 
    <ModelC: id 3, field1 (CharField), field2 (CharField), field3 (CharField)> ] 

考慮到這些查詢會slightly less performant