Django将Model的字段类型从CharField更改为JSONField [英] Django change Model's field type from CharField to JSONField
问题描述
我正在使用 Django 1.11
,我一直在模型中使用 CharField
,并使用 json.dumps()
。我正在使用 mysql
数据库。
I am using Django 1.11
, I have been using CharField
in Models, and dumping data in it using json.dumps()
. I am using mysql
database.
我想更改 CharField
到 JSONField
,根据此答案。有什么方法可以修改我的字段类型而不丢失数据吗?
I want to change CharField
to JSONField
, according to this answer. Is there any way so that I can modify my field type without loosing the data?
请注意,CharField中的数据是json转储的。
Please note that the data in CharField is json dumped.
推荐答案
如果要完全控制流程,请编写自定义迁移:
If you want to completely control the process write custom migration:
1)添加新字段类型为JSONField null = True
1) add new field of type JSONField null=True
2)使用
和 RunPython
使用自定义空迁移将数据复制到那里 https://docs.djangoproject .com / zh-CN / 2.0 / ref / migration-operations /#django.db.migrations.operations.RunPython 首先
2) copy data there using custom empty migration with
with RunPython
https://docs.djangoproject.com/en/2.0/ref/migration-operations/#django.db.migrations.operations.RunPython first
3)检查是否已复制所有内容
3) check everything was copied ok
4)删除旧字段
5)最终处理字段重命名
5) handle field rename eventually
这篇关于Django将Model的字段类型从CharField更改为JSONField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!