【问题标题】:Field diamond pattern in multiple abstract model inheritance in Python/DjangoPython / Django中多个抽象模型继承中的字段菱形模式
【发布时间】:2015-03-12 14:56:48
【问题描述】:

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

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 抽象,也无济于事:

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

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

【问题讨论】:

  • 奇怪的是,models.AutoField(primary_key=True) 根据文档工作。
  • @dmg 我猜你指的是multiple inheritance 上的文档。诀窍是一个名为idAutoField 被隐式添加到Piece。子模型继承此字段,因此它们已经有一个主键。这可以防止添加新的隐式 id 字段 -> 没有名称冲突。这并不意味着您可以覆盖父字段。

标签: python django python-3.x multiple-inheritance diamond-problem


【解决方案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()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 2013-10-21
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多