2011-05-16 51 views
7

我在我的一些Django模型中使用JSONField並希望將這些數據從Oracle遷移到Postgres。Django JSONField傾銷/加載

到目前爲止,使用Django的dumpdata和loaddata命令時,我還沒有保留這個JSON數據的任何運氣,數據被轉換爲JSON的字符串表示形式。我還沒有找到一個很好的解決方案......想法?

回答

6

我最終解決了這個問題,方法是在一個名爲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序列化很好,而另一些則沒有。這就是爲什麼我採取了指定要處理的字段的方法。現在所有數據都正確序列化。

0

我以前沒有使用過的JSONField,但我做的是:

import json 

data_structure = json.loads(myData) 

也許這會爲你需要什麼,以及工作。有可能有更好的方法來處理這個問題。

0

編輯:如果你最終使用包json - 只有那麼下面的解決方案適用。

如果您正在使用Python 2.6及以上,你可以使用:

import json 

否則,您可以使用捆綁django.utils(對於Python 2.6 <)的simplejson。

from django.utils import simplejson as json 

這樣,您可以繼續使用相同的包名,並把你的代碼,谷歌應用程序引擎,因爲它支持Python 2.5.2的時刻。