Django foreign keys violate multiple-valued inheritance

The following code works as I expect:

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

I can create a general, add captains, and make "general.captains" work as expected.

But when both of these classes inherit the base class, which may have additional information, disaster strikes.

 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 

Any idea what could be happening here, and how can I fix it?

+4
source share
1 answer

It should work if you explicitly define the Officer model as abstract

 class Meta: abstract = True 

So, as a test, I slightly modified your base class:

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

And the following works:

 >>> 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' 
0
source

Source: https://habr.com/ru/post/1339512/


All Articles