gpt4 book ai didi

python - 模型子类 : override CharField max_length

转载 作者:太空宇宙 更新时间:2023-11-04 03:37:35 26 4
gpt4 key购买 nike

我有一个提供的数据库模式,我想为其创建一个 Django 应用程序。架构中的许多表共享一组通用的列,例如 namedate_created。这促使我创建一个包含这些列的抽象 Standard_model 类,并从中子类化相关模型。

不幸的是,某些表的 name 列具有不同的 max_length。我试图想出一种方法,让子类化模型将 max_length 值传递给抽象基类,但我一片空白。

有什么想法吗?

class Standard_model(models.Model):
name = models.CharField(max_length=50)
date_created = models.DateTimeField()

class Meta:
abstract = True

class MyModel(Standard_model):
name = models.CharField(max_length=80) # Can't do this.

最佳答案

不,你cannot override the name field definition :

In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this is not permitted for attributes that are Field instances (at least, not at the moment). If a base class has a field called author, you cannot create another model field called author in any class that inherits from that base class.

另见:

并且,仅供引用,根据 model naming convention ,它应该被称为 StandardModel

关于python - 模型子类 : override CharField max_length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28196453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com