Django继承和子类属性

时间:2015-05-28 17:43:32

标签: python django inheritance subclass

使用如下配置:

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似乎将其视为A的实例,而我无法访问c.a.subclass_attribute。有没有解决的办法?由于ForeignKeys的困难,我不想使用抽象继承 - 我希望C支持A的任何子类。

1 个答案:

答案 0 :(得分:1)

您可以使用django-polymorphic来解决ForeignKey的问题。

Django Polymorphic允许您查询基类对象但检索子类实例:

>>> 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 polymorphic,您只需要将多态模型声明为基类:

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