我有一个提供的数据库模式,我想为其创建一个 Django 应用程序。架构中的许多表共享一组通用的列,例如 name 和 date_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。
