目的是拥有一个可以被其他模型嵌套的BaseModel
注意: BaseModel 不应写入数据库
所以我有一个如下所示的 BaseModel
class StaticVariable(models.Model):
class Meta:
managed = False
title = models.CharField(
max_length=250, blank=False, null=False
)
alias = models.CharField(
max_length=250, blank=False, null=False, unique=True
)
created_at = models.DateTimeField(
auto_now_add=True, blank=False, null=False
)
updated_at = models.DateTimeField(
auto_now=True, blank=False, null=False
)
enabled = models.BooleanField(
default=True, blank=False, null=False
)
deleted = models.BooleanField(
default=False, blank=False, null=False
)
我进行了迁移并应用了它,因为 Meta 类具有 management=False 参数,因此未创建实际的 SQL 表(如预期)
之后,我创建新模型,该模型从 StaticVariable 模型嵌套作为基础
class BodyType(StaticVariable):
class Meta:
db_table = 'body_type'
ordering = ["title", "-id"]
然后我进行迁移,看起来像这样
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('utils', '0004_staticvariable'),
('app', '0002_alter_category_enabled'),
]
operations = [
migrations.CreateModel(
name='BodyType',
fields=[
('staticvariable_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='utils.staticvariable')),
],
options={
'db_table': 'body_type',
'ordering': ['title', '-id'],
},
bases=('utils.staticvariable',),
),
]
但是,当我尝试迁移时,出乎意料地我发现了以下错误
Running migrations:
Applying app.0003_bodytype...Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 87, in _execute
return self.cursor.execute(sql)
File "/usr/local/lib/python3.10/site-packages/psycopg/cursor.py", line 737, in execute
raise ex.with_traceback(None)
psycopg.errors.UndefinedTable: relation "utils_staticvariable" does not exist
我想这是因为 BaseModel 没有写入数据库,但我不想将空表写入数据库
当您从模型继承时,Django 默认会与基础模型建立
one-to-one
关系,这就是为什么它会尝试在您的 staticvariable_ptr
模型中创建一个指向 BodyType
实例的 StaticVariable
字段。
正如您的代码中
StaticVariable
有managed = False
一样,Django不管理此模型的数据库表,这会导致您面临的错误。
要解决这个问题,您应该使用抽象基类(参考。Django Abstract Base Class)
您可以通过在
abstract = True
模型的 Meta 类中设置 StaticVariable
来定义抽象基类,如下所示:
class StaticVariable(models.Model):
class Meta:
abstract = True
进行这些更改后,请确保进行新的迁移并进行迁移。