Ticket #4714: json.diff
File json.diff, 7.8 KB (added by , 17 years ago) |
---|
-
django/core/serializers/python.py
13 13 """ 14 14 Serializes a QuerySet to basic Python objects. 15 15 """ 16 17 def str_to_unicode(self, val): 18 """ Converts all strings to unicode and leaves other types as they are 19 smart_unicode(strings_only=True, ...) is not used as it only 20 recognizes 'types.NoneType' and 'int' as not strings 21 """ 22 if not isinstance(val, basestring,): 23 return val 24 return smart_unicode(val) 16 25 17 26 def start_serialization(self): 18 27 self._current = None … … 27 36 def end_object(self, obj): 28 37 self.objects.append({ 29 38 "model" : smart_unicode(obj._meta), 30 "pk" : s mart_unicode(obj._get_pk_val()),39 "pk" : self.str_to_unicode(obj._get_pk_val()), 31 40 "fields" : self._current 32 41 }) 33 42 self._current = None 34 43 35 44 def handle_field(self, obj, field): 36 self._current[field.name] = getattr(obj, field.name)45 self._current[field.name] = self.str_to_unicode(getattr(obj, field.name)) 37 46 38 47 def handle_fk_field(self, obj, field): 39 48 related = getattr(obj, field.name) … … 44 53 else: 45 54 # Related to remote object via other field 46 55 related = getattr(related, field.rel.field_name) 47 self._current[field.name] = related56 self._current[field.name] = self.str_to_unicode(related) 48 57 49 58 def handle_m2m_field(self, obj, field): 50 self._current[field.name] = [related._get_pk_val() for related in getattr(obj, field.name).iterator()] 59 self._current[field.name] = [self.str_to_unicode(related._get_pk_val())\ 60 for related in getattr(obj, field.name).iterator()] 51 61 52 62 def getvalue(self): 53 63 return self.objects -
tests/modeltests/serializers/models.py
1 # -*- coding: utf-8 -*- 1 2 """ 2 3 41. Serialization 3 4 … … 43 44 44 45 def __unicode__(self): 45 46 return u"Profile of %s" % self.author 47 48 class Actor(models.Model): 49 name = models.CharField(max_length=20, primary_key=True) 46 50 51 class Meta: 52 ordering = ('name',) 53 54 def __unicode__(self): 55 return self.name 56 57 class Movie(models.Model): 58 actor = models.ForeignKey(Actor) 59 title = models.CharField(max_length=50) 60 61 class Meta: 62 ordering = ('title',) 63 64 def __unicode__(self): 65 return self.title 66 47 67 __test__ = {'API_TESTS':""" 48 68 # Create some data: 49 69 >>> from datetime import datetime … … 101 121 # Django also ships with a built-in JSON serializers 102 122 >>> json = serializers.serialize("json", Category.objects.filter(pk=2)) 103 123 >>> json 104 '[{"pk": "2", "model": "serializers.category", "fields": {"name": "Music"}}]'124 '[{"pk": 2, "model": "serializers.category", "fields": {"name": "Music"}}]' 105 125 106 126 # You can easily create new objects by deserializing data with an empty PK 107 127 # (It's easier to demo this with JSON...) … … 133 153 134 154 >>> json = serializers.serialize("json", AuthorProfile.objects.all()) 135 155 >>> json 136 '[{"pk": "1", "model": "serializers.authorprofile", "fields": {"date_of_birth": "1970-01-01"}}]'156 '[{"pk": 1, "model": "serializers.authorprofile", "fields": {"date_of_birth": "1970-01-01"}}]' 137 157 138 158 >>> for obj in serializers.deserialize("json", json): 139 159 ... print obj … … 141 161 142 162 # Objects ids can be referenced before they are defined in the serialization data 143 163 # However, the deserialization process will need to be contained within a transaction 144 >>> 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"}}]'164 >>> 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"}}]' 145 165 >>> from django.db import transaction 146 166 >>> transaction.enter_transaction_management() 147 167 >>> transaction.managed(True) … … 161 181 162 182 # Serializer output can be restricted to a subset of fields 163 183 >>> print serializers.serialize("json", Article.objects.all(), fields=('headline','pub_date')) 164 [{"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"}}]184 [{"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"}}] 165 185 186 # Every string is serialized as a unicode object, also primary key 187 # which is 'varchar' 188 >>> ac = Actor(name="Zażółć") 189 >>> mv = Movie(title="Gęślą jaźń", actor=ac) 190 >>> ac.save(); mv.save() 191 192 # Let's serialize our movie 193 >>> print serializers.serialize("json", [mv]) 194 [{"pk": 1, "model": "serializers.movie", "fields": {"actor": "Za\u017c\u00f3\u0142\u0107", "title": "G\u0119\u015bl\u0105 ja\u017a\u0144"}}] 195 196 # Deserialization of movie 197 >>> list(serializers.deserialize('json', serializers.serialize('json', [mv])))[0].object.title 198 u'G\u0119\u015bl\u0105 ja\u017a\u0144' 199 200 # None is null after serialization to json 201 # Primary key is None in case of not saved model 202 >>> mv2 = Movie(title="Movie 2", actor=ac) 203 >>> print serializers.serialize("json", [mv2]) 204 [{"pk": null, "model": "serializers.movie", "fields": {"actor": "Za\u017c\u00f3\u0142\u0107", "title": "Movie 2"}}] 205 206 # Deserialization of null returns None for pk 207 >>> print list(serializers.deserialize('json', serializers.serialize('json', [mv2])))[0].object.id 208 None 209 166 210 """} -
tests/modeltests/fixtures/models.py
74 74 75 75 # Dump the current contents of the database as a JSON fixture 76 76 >>> management.call_command('dumpdata', 'fixtures', format='json') 77 [{"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"}}]77 [{"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"}}] 78 78 """} 79 79 80 80 from django.test import TestCase