Django将Model的字段类型从CharField更改为JSONField [英] Django change Model's field type from CharField to JSONField

查看:254
本文介绍了Django将Model的字段类型从CharField更改为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆