Python/Djang中多抽象模型继承中的字段菱形模式

2024-10-01 07:44:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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:

^{pr2}$

即使我声明船是抽象的,也无济于事:

shop.Amphibious.createTS: (models.E006) The field 'createTS' clashes with the field 'createTS' from model 'shop.amphibious'.

有没有可能拥有一个具有多重继承和一个公共基类的模型类层次结构(模型。模型子类)声明一些字段?在


Tags: from模型abstracttrueauto层次结构modelspass
1条回答
网友
1楼 · 发布于 2024-10-01 07:44:31

用这个看看是否有用。如果您试图在模型中包含时间戳,那么只需创建一个只包含时间戳的基本模型。在

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个月了。如果你已经找到了一个更好的解决方案,那么请与我们分享,将有助于我们学习。:)

相关问题 更多 >