Python/Django中多个抽象模型继承中的场菱形图案

STF*_*STF 5 python django multiple-inheritance diamond-problem python-3.x

我有以下模型类层次结构:

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
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不适用于Django:

shop.Amphibious.createTS: (models.E006) The field 'createTS' clashes with the field 'createTS' from model 'shop.boat'.
Run Code Online (Sandbox Code Playgroud)

即使我宣布船抽象,它也无济于事:

shop.Amphibious.createTS: (models.E006) The field 'createTS' clashes with the field 'createTS' from model 'shop.amphibious'.
Run Code Online (Sandbox Code Playgroud)

是否可以使用具有多重继承的模型类层次结构和声明某些字段的公共基类(models.Model子类)?

Min*_*nnR 1

使用这个看看是否有帮助。如果您尝试将时间戳包含到模型中,则只需创建一个仅包含时间戳的基本模型。

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()
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。我看到你提出这个问题已经过去5个月了。如果您已经找到了更好的解决方案,请与我们分享,这将对我们的学习有很大帮助。:)