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

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

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

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/

相关文章:

python - 基于每日时间序列数据框创建工作日/周末时间序列数据框

python - 如果元组中的 string1 或 string2

Python - 检查字母是否出现在连续的单词中

python - 为什么第一行更长?

python - 为什么在 Django 中重写 Model.save() 函数不起作用?

python - 通过@property 订购 Django 查询集

python - 根据行值返回列的平均值

python - 如何在discord.py中获取用户的头像及其id?

python - 如何在自定义非管理模型中使用 'set_password'?

python - 如何用 python 解析 yaml 字符串?