Django JSONField转储/加载

Ian*_*Ian 8 django json

我在我的一些Django模型中使用JSONField,并希望将这些数据从Oracle迁移到Postgres.

到目前为止,当使用Django的dumpdata和loaddata命令时,我没有幸运地保持这个JSON数据完整,数据被转换为JSON的字符串表示.我还没有找到一个很好的解决方案...想法?

Ian*_*Ian 8

我最终通过在名为custom_json_serializer.py的自定义序列化程序文件中覆盖Django包含的JSON序列化程序(特别是handle_field方法)来解决此问题.通过这样做,我可以确保特定的JSONField保持原样,而不是转换为字符串.

关于其他人遇到这个问题的机会,这些是我采取的步骤.我不得不将这个自定义序列化程序添加到settings.py文件中:

SERIALIZATION_MODULES = {       
    'custom_json': 'myapp.utils.custom_json_serializer',
}
Run Code Online (Sandbox Code Playgroud)

然后在从Django序列化数据时调用它:

python manage.py dumpdata mymodel --format=custom_json --indent=2 --traceback > mymodel_data.json
Run Code Online (Sandbox Code Playgroud)

自定义序列化程序如下所示:

from django.core.serializers.json import Serializer as JSONSerializer
from django.utils.encoding import is_protected_type

# JSONFields that are normally incorrectly serialized as strings
json_fields = ['problem_field1', 'problem_field2']


class Serializer(JSONSerializer):
    """
    A fix on JSONSerializer in order to prevent stringifying JSONField data.
    """
    def handle_field(self, obj, field):
        value = field._get_val_from_obj(obj)
        # Protected types (i.e., primitives like None, numbers, dates,
        # and Decimals) are passed through as is. All other values are
        # converted to string first.
        if is_protected_type(value) or field.name in json_fields:
            self._current[field.name] = value
        else:
            self._current[field.name] = field.value_to_string(obj)
Run Code Online (Sandbox Code Playgroud)

真正奇怪的是,在此修复之前,一些JSONFields正在序列化,而其他人则没有.这就是为什么我采用指定要处理的字段的方法.现在所有数据都正确序列化.