Django外键打破多表继承

时间:2011-02-13 01:44:25

标签: django django-models

以下代码按我的预期工作:

class General(Model):
    pass

class Captain(Model):
    general = ForeignKey('General',related_name='captains')

我可以创建一个通用,添加队长,并且“general.captains”按预期工作。

但是当这两个类继承自可能有额外信息的基类时,就会发生灾难。

class Officer(Model):
    pass

class General(Officer):
    pass

class Captain(Officer):
    general = ForeignKey('General',related_name='captains')


>>> g = General()
>>> g.captains
    Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Python27\lib\site-packages\django\db\models\fields\related.py", line
391, in __get__
    self.related.model._default_manager.__class__)
  File "C:\Python27\lib\site-packages\django\db\models\fields\related.py", line
469, in create_manager
    getattr(instance, attname)}
  File "C:\Python27\lib\site-packages\django\db\models\fields\related.py", line
301, in __get__
    raise self.field.rel.to.DoesNotExist
DoesNotExist

知道这里可能会发生什么,以及我如何解决它?

1 个答案:

答案 0 :(得分:0)

如果您将Officer模型明确定义为abstract

,它应该有效
class Meta:
    abstract = True

因此,作为测试,我稍微修改了您的基类:

class Officer(models.Model):
    name = models.CharField(max_length=255)
    class Meta:
       abstract = True

以下作品:

>>> General(name='Warfield').save()
>>> G = General.objects.all()[0]
>>> Captain(name='Picard', general=G).save()
>>> C = Captain.objects.all()[0]    
>>> C.general.name
u'Warfield'
>>> G.captains.all()[0].name
u'Picard'