繁体   English   中英

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

[英]Field diamond pattern in multiple abstract model inheritance in Python/Django

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

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'.

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

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

是否可以使用具有多重继承的模型类层次结构和声明某些字段的公共基类(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个月了。 如果您已经找到了更好的解决方案,那么请与我们分享,这将有助于我们学习。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM