1
|
import json
|
2
|
import sys
|
3
|
|
4
|
from django.utils import six
|
5
|
from django.core.serializers.json import Serializer as JSONSerializer
|
6
|
from django.core.serializers.python import Deserializer as \
|
7
|
PythonDeserializer, _get_model
|
8
|
from django.core.serializers.base import DeserializationError
|
9
|
|
10
|
class Serializer(JSONSerializer):
|
11
|
def get_dump_object(self, obj):
|
12
|
d = super(Serializer, self).get_dump_object(obj)
|
13
|
if self.use_natural_keys and hasattr(obj, 'natural_key'):
|
14
|
d['pk'] = obj.natural_key()
|
15
|
return d
|
16
|
|
17
|
def Deserializer(stream_or_string, **options):
|
18
|
"""
|
19
|
Deserialize a stream or string of JSON data.
|
20
|
"""
|
21
|
if not isinstance(stream_or_string, (bytes, six.string_types)):
|
22
|
stream_or_string = stream_or_string.read()
|
23
|
if isinstance(stream_or_string, bytes):
|
24
|
stream_or_string = stream_or_string.decode('utf-8')
|
25
|
try:
|
26
|
objects = json.loads(stream_or_string)
|
27
|
for obj in objects:
|
28
|
Model = _get_model(obj['model'])
|
29
|
if isinstance(obj['pk'], (tuple, list)):
|
30
|
try:
|
31
|
o = Model.objects.get_by_natural_key(*obj['pk'])
|
32
|
except Model.DoesNotExist:
|
33
|
obj['pk'] = None
|
34
|
else:
|
35
|
obj['pk'] = o.pk
|
36
|
for obj in PythonDeserializer(objects, **options):
|
37
|
yield obj
|
38
|
except GeneratorExit:
|
39
|
raise
|
40
|
except Exception as e:
|
41
|
# Map to deserializer error
|
42
|
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
|
43
|
|
44
|
|