Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python/Django中多抽象模型继承中的字段菱形模式_Python_Django_Python 3.x_Multiple Inheritance_Diamond Problem - Fatal编程技术网

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

Python/Django中多抽象模型继承中的字段菱形模式,python,django,python-3.x,multiple-inheritance,diamond-problem,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 = T

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

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

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

奇怪的是,
models.AutoField(primary\u key=True)
是根据文档工作的。@dmg我猜您指的是上的文档。诀窍在于将名为
id
自动字段
隐式添加到
片段
。子模型继承此字段,因此它们已经具有主键。这将防止添加新的隐式
id
字段->无名称冲突。无论如何,这并不意味着您可以覆盖父字段。