我有以下模型类层次结构:
from django.db import models
class Entity(models.Model):
createTS = models.DateTimeField(auto_now=False, auto_now_add=True)
class Meta:
abstract = True
class Car(Entity):
pass
class Meta:
abstract = True
class Boat(Entity):
pass
class Amphibious(Boat,Car):
pass
不幸的是,这不适用于 Django:
shop.Amphibious.createTS: (models.E006) The field 'createTS' clashes with the field 'createTS' from model 'shop.boat'.
即使我声明 Boat abstract,也无济于事:
shop.Amphibious.createTS: (models.E006) The field 'createTS' clashes with the field 'createTS' from model 'shop.amphibious'.
是否可以有一个具有多重继承的模型类层次结构和一个声明一些字段的公共(public)基类(models.Model 子类)?
最佳答案
使用它,看看它是否有帮助。如果您尝试将时间戳包含到模型中,则只需创建一个仅包含时间戳的基本模型。
from django.db import models
class Base(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Boat(Base):
boat_fields_here = models.OnlyBoatFields()
class Amphibious(Boat):
# The boat fields will already be added so now just add
# the car fields and that will make this model Amphibious
car_fields_here = models.OnlyCarFields()
希望对您有所帮助。我看到你发布这个问题已经 5 个月了。如果您已经找到更好的解决方案,请与我们分享,这将对我们的学习有很大帮助。 :)
关于python - Python/Django 中多抽象模型继承中的字段菱形模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27942706/