Code

Ticket #4714: json.diff

File json.diff, 7.8 KB (added by pigletto, 7 years ago)

Patch against revision 6193

Line 
1Index: django/core/serializers/python.py
2===================================================================
3--- django/core/serializers/python.py   (wersja 6184)
4+++ django/core/serializers/python.py   (kopia robocza)
5@@ -13,6 +13,15 @@
6     """
7     Serializes a QuerySet to basic Python objects.
8     """
9+   
10+    def str_to_unicode(self, val):
11+        """ Converts all strings to unicode and leaves other types as they are
12+            smart_unicode(strings_only=True, ...) is not used as it only
13+            recognizes 'types.NoneType' and 'int' as not strings
14+        """
15+        if not isinstance(val, basestring,):
16+            return val
17+        return smart_unicode(val)
18 
19     def start_serialization(self):
20         self._current = None
21@@ -27,13 +36,13 @@
22     def end_object(self, obj):
23         self.objects.append({
24             "model"  : smart_unicode(obj._meta),
25-            "pk"     : smart_unicode(obj._get_pk_val()),
26+            "pk"     : self.str_to_unicode(obj._get_pk_val()),
27             "fields" : self._current
28         })
29         self._current = None
30 
31     def handle_field(self, obj, field):
32-        self._current[field.name] = getattr(obj, field.name)
33+        self._current[field.name] = self.str_to_unicode(getattr(obj, field.name))
34 
35     def handle_fk_field(self, obj, field):
36         related = getattr(obj, field.name)
37@@ -44,10 +53,11 @@
38             else:
39                 # Related to remote object via other field
40                 related = getattr(related, field.rel.field_name)
41-        self._current[field.name] = related
42+        self._current[field.name] = self.str_to_unicode(related)
43 
44     def handle_m2m_field(self, obj, field):
45-        self._current[field.name] = [related._get_pk_val() for related in getattr(obj, field.name).iterator()]
46+        self._current[field.name] = [self.str_to_unicode(related._get_pk_val())\
47+                           for related in getattr(obj, field.name).iterator()]
48 
49     def getvalue(self):
50         return self.objects
51Index: tests/modeltests/serializers/models.py
52===================================================================
53--- tests/modeltests/serializers/models.py      (wersja 6184)
54+++ tests/modeltests/serializers/models.py      (kopia robocza)
55@@ -1,3 +1,4 @@
56+# -*- coding: utf-8 -*-
57 """
58 41. Serialization
59 
60@@ -43,7 +44,26 @@
61     
62     def __unicode__(self):
63         return u"Profile of %s" % self.author
64+       
65+class Actor(models.Model):
66+    name = models.CharField(max_length=20, primary_key=True)
67 
68+    class Meta:
69+        ordering = ('name',)
70+   
71+    def __unicode__(self):
72+        return self.name
73+   
74+class Movie(models.Model):
75+    actor = models.ForeignKey(Actor)
76+    title = models.CharField(max_length=50)
77+
78+    class Meta:
79+       ordering = ('title',)
80+
81+    def __unicode__(self):
82+        return self.title
83+
84 __test__ = {'API_TESTS':"""
85 # Create some data:
86 >>> from datetime import datetime
87@@ -101,7 +121,7 @@
88 # Django also ships with a built-in JSON serializers
89 >>> json = serializers.serialize("json", Category.objects.filter(pk=2))
90 >>> json
91-'[{"pk": "2", "model": "serializers.category", "fields": {"name": "Music"}}]'
92+'[{"pk": 2, "model": "serializers.category", "fields": {"name": "Music"}}]'
93 
94 # You can easily create new objects by deserializing data with an empty PK
95 # (It's easier to demo this with JSON...)
96@@ -133,7 +153,7 @@
97 
98 >>> json = serializers.serialize("json", AuthorProfile.objects.all())
99 >>> json
100-'[{"pk": "1", "model": "serializers.authorprofile", "fields": {"date_of_birth": "1970-01-01"}}]'
101+'[{"pk": 1, "model": "serializers.authorprofile", "fields": {"date_of_birth": "1970-01-01"}}]'
102 
103 >>> for obj in serializers.deserialize("json", json):
104 ...     print obj
105@@ -141,7 +161,7 @@
106 
107 # Objects ids can be referenced before they are defined in the serialization data
108 # However, the deserialization process will need to be contained within a transaction
109->>> json = '[{"pk": "3", "model": "serializers.article", "fields": {"headline": "Forward references pose no problem", "pub_date": "2006-06-16 15:00:00", "categories": [4, 1], "author": 4}}, {"pk": "4", "model": "serializers.category", "fields": {"name": "Reference"}}, {"pk": "4", "model": "serializers.author", "fields": {"name": "Agnes"}}]'
110+>>> json = '[{"pk": 3, "model": "serializers.article", "fields": {"headline": "Forward references pose no problem", "pub_date": "2006-06-16 15:00:00", "categories": [4, 1], "author": 4}}, {"pk": 4, "model": "serializers.category", "fields": {"name": "Reference"}}, {"pk": 4, "model": "serializers.author", "fields": {"name": "Agnes"}}]'
111 >>> from django.db import transaction
112 >>> transaction.enter_transaction_management()
113 >>> transaction.managed(True)
114@@ -161,6 +181,30 @@
115 
116 # Serializer output can be restricted to a subset of fields
117 >>> print serializers.serialize("json", Article.objects.all(), fields=('headline','pub_date'))
118-[{"pk": "1", "model": "serializers.article", "fields": {"headline": "Just kidding; I love TV poker", "pub_date": "2006-06-16 11:00:00"}}, {"pk": "2", "model": "serializers.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": "3", "model": "serializers.article", "fields": {"headline": "Forward references pose no problem", "pub_date": "2006-06-16 15:00:00"}}]
119+[{"pk": 1, "model": "serializers.article", "fields": {"headline": "Just kidding; I love TV poker", "pub_date": "2006-06-16 11:00:00"}}, {"pk": 2, "model": "serializers.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 3, "model": "serializers.article", "fields": {"headline": "Forward references pose no problem", "pub_date": "2006-06-16 15:00:00"}}]
120 
121+# Every string is serialized as a unicode object, also primary key
122+# which is 'varchar'
123+>>> ac = Actor(name="Zażółć")
124+>>> mv = Movie(title="Gęślą jaźń", actor=ac)
125+>>> ac.save(); mv.save()
126+
127+# Let's serialize our movie
128+>>> print serializers.serialize("json", [mv])
129+[{"pk": 1, "model": "serializers.movie", "fields": {"actor": "Za\u017c\u00f3\u0142\u0107", "title": "G\u0119\u015bl\u0105 ja\u017a\u0144"}}]
130+
131+# Deserialization of movie
132+>>> list(serializers.deserialize('json', serializers.serialize('json', [mv])))[0].object.title
133+u'G\u0119\u015bl\u0105 ja\u017a\u0144'
134+
135+# None is null after serialization to json
136+# Primary key is None in case of not saved model
137+>>> mv2 = Movie(title="Movie 2", actor=ac)
138+>>> print serializers.serialize("json", [mv2])
139+[{"pk": null, "model": "serializers.movie", "fields": {"actor": "Za\u017c\u00f3\u0142\u0107", "title": "Movie 2"}}]
140+
141+# Deserialization of null returns None for pk
142+>>> print list(serializers.deserialize('json', serializers.serialize('json', [mv2])))[0].object.id
143+None
144+
145 """}
146Index: tests/modeltests/fixtures/models.py
147===================================================================
148--- tests/modeltests/fixtures/models.py (wersja 6184)
149+++ tests/modeltests/fixtures/models.py (kopia robocza)
150@@ -74,7 +74,7 @@
151 
152 # Dump the current contents of the database as a JSON fixture
153 >>> management.call_command('dumpdata', 'fixtures', format='json')
154-[{"pk": "3", "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": "2", "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": "1", "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]
155+[{"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]
156 """}
157 
158 from django.test import TestCase