我在我的一些Django模型中使用JSONField并希望将这些数据从Oracle迁移到Postgres。Django JSONField倾销/加载
到目前为止,使用Django的dumpdata和loaddata命令时,我还没有保留这个JSON数据的任何运气,数据被转换为JSON的字符串表示形式。我还没有找到一个很好的解决方案......想法?
我在我的一些Django模型中使用JSONField并希望将这些数据从Oracle迁移到Postgres。Django JSONField倾销/加载
到目前为止,使用Django的dumpdata和loaddata命令时,我还没有保留这个JSON数据的任何运气,数据被转换为JSON的字符串表示形式。我还没有找到一个很好的解决方案......想法?
我最终解决了这个问题,方法是在一个名为custom_json_serializer.py的自定义序列化程序文件中重写Django包含的JSON序列化程序,特别是handle_field方法。通过这样做,我可以确保特定的JSONFields保持不变,而不会转换为字符串。
就其他人遇到此问题的机会而言,这些是我采取的步骤。我只好这个自定义序列化添加到settings.py文件:
SERIALIZATION_MODULES = {
'custom_json': 'myapp.utils.custom_json_serializer',
}
,然后把它从Django的序列化数据时:
python manage.py dumpdata mymodel --format=custom_json --indent=2 --traceback > mymodel_data.json
的自定义序列的样子:
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)
真奇怪的部分是,在修复之前,一些JSONFields序列化很好,而另一些则没有。这就是为什么我采取了指定要处理的字段的方法。现在所有数据都正确序列化。
我以前没有使用过的JSONField,但我做的是:
import json
data_structure = json.loads(myData)
也许这会为你需要什么,以及工作。有可能有更好的方法来处理这个问题。
编辑:如果你最终使用包json - 只有那么下面的解决方案适用。
如果您正在使用Python 2.6及以上,你可以使用:
import json
否则,您可以使用捆绑django.utils(对于Python 2.6 <)的simplejson。
from django.utils import simplejson as json
这样,您可以继续使用相同的包名,并把你的代码,谷歌应用程序引擎,因为它支持Python 2.5.2的时刻。