我创建了一个 Django 应用程序,并且有一个如下所示的模型:
class Company(models.Model):
name = models.TextField(max_length = 200)
当我运行python3 manage.py makemigrations appname
时,一切都按预期工作,并且创建了该类的迁移文件。
如果模型中的类也定义了 Meta
类,就会出现问题:
class Company(models.Model):
name = models.TextField(max_length = 200)
class Meta:
app_label = "Companies"
现在,如果我运行 makemigrations
命令,我要么收到“未检测到更改”消息,并且不会生成迁移文件:
> python3 manage.py makemigrations myApp
No changes detected in app 'appname'
或者,更糟糕的是,如果具有 Meta
类的模型没有依赖项(外键),则创建的迁移将完全删除模型/表。
或者,如果存在依赖关系(来自另一个模型的外键引用),我会收到如下错误:
matcher.OtherTable.foreignkeyref: (fields.E300) Field defines a relation with model 'Company', which is either not installed, or is abstract.
定义了 Meta
类的所有模型都不会生成迁移,无论是初始迁移还是出于某种原因的任何后续迁移。事后添加元的类将在下次迁移时删除。就好像它们根本不存在一样。
我在 Mac OS 10.15.5 上使用 Python 3.8.3 和 Django 3.0.6。
最佳答案
All models with a
Meta
class defined will not generate a migration, either an initial one or any subsequent migration for some reason. Classes that haveMeta
added after the fact will be removed at the next migration.
问题是你改变了app_label
,现在你说这个模型不属于它最初所属的应用程序,而是属于其他地方。因此,对于该应用程序,模型已“消失”,而对于新应用程序(此处为Companies
),模型“凭空出现”。正如 documentation 中指定的那样,在以下情况下使用 app_label
:
If a model is defined outside of an application in INSTALLED_APPS, it must declare which app it belongs to (…).
指定 app_label
的情况相当罕见。如果您不指定它,它将采用定义它的应用程序的名称。
但是,您似乎覆盖了错误的设置。根据您传递给它的值,您可能需要指定 verbose_name_plural
option [Django-doc] :
class Company(models.Model):
name = models.TextField(max_length = 200)
class Meta:
<b>verbose_name_plural</b> = "Companies"
关于python - Django 数据库迁移因添加 "Meta"类而停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62012041/