问题描述
我已经在模型中添加了一个字段。但是我已经通过自定义sql查询(更改字段)将字段添加到数据库中的模型中。现在,当我尝试创建其他迁移文件时,Django将创建迁移以将字段添加到数据库中的该模型。
如何使django不这样做?
I have added a field to my model. But I have added the field to the model in DB through a custom sql query(Alter Field). Now when I try to create other Migration files, Django creates migration for adding the field to that model in DB.How to make django not do this?
我需要在添加对另一个字段的引用之前修改字段的排序规则。
Django更改字段确实会更改表添加字段,AlterTable添加参考
而我想要更改表添加字段,修改字段排序规则,AlterTable添加参考。
自定义sql查询写在迁移文件中。
I needed to do modify the collation of the field before adding a reference to another field.Django Alter Field does Alter Table-Add Field,AlterTable-Add ReferenceWhile I wanted Alter Table-Add Field,Modify Field Collation,AlterTable-Add Reference.The custom sql query is written inside a migration file.
推荐答案
您可以使用来创建具有正确排序规则的字段。调用RunSQL时,使用 state_operations
参数提供状态更改,以使您的SQL代码保持Django最新。
You can use RunSQL to create the field with the proper collation. When calling RunSQL use the state_operations
argument to supply the state changes your SQL code made to keep Django up-to-date.
以下是Django文档的示例:
Here's an example from Django's documentation:
from django.db import migrations
class Migration(migrations.Migration):
operations = [
migrations.RunSQL(
"ALTER TABLE musician ADD COLUMN name varchar(255) NOT NULL;",
state_operations=[
migrations.AddField(
'musician',
'name',
models.CharField(max_length=255),
),
],
),
]
这篇关于使用Django未检测到的使用自定义SQL添加的模型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!