Ticket #4714: json.diff

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

Patch against revision 6193

  • django/core/serializers/python.py

     
    1313    """
    1414    Serializes a QuerySet to basic Python objects.
    1515    """
     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)
    1625
    1726    def start_serialization(self):
    1827        self._current = None
     
    2736    def end_object(self, obj):
    2837        self.objects.append({
    2938            "model"  : smart_unicode(obj._meta),
    30             "pk"     : smart_unicode(obj._get_pk_val()),
     39            "pk"     : self.str_to_unicode(obj._get_pk_val()),
    3140            "fields" : self._current
    3241        })
    3342        self._current = None
    3443
    3544    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))
    3746
    3847    def handle_fk_field(self, obj, field):
    3948        related = getattr(obj, field.name)
     
    4453            else:
    4554                # Related to remote object via other field
    4655                related = getattr(related, field.rel.field_name)
    47         self._current[field.name] = related
     56        self._current[field.name] = self.str_to_unicode(related)
    4857
    4958    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()]
    5161
    5262    def getvalue(self):
    5363        return self.objects
  • tests/modeltests/serializers/models.py

     
     1# -*- coding: utf-8 -*-
    12"""
    2341. Serialization
    34
     
    4344   
    4445    def __unicode__(self):
    4546        return u"Profile of %s" % self.author
     47       
     48class Actor(models.Model):
     49    name = models.CharField(max_length=20, primary_key=True)
    4650
     51    class Meta:
     52        ordering = ('name',)
     53   
     54    def __unicode__(self):
     55        return self.name
     56   
     57class 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
    4767__test__ = {'API_TESTS':"""
    4868# Create some data:
    4969>>> from datetime import datetime
     
    101121# Django also ships with a built-in JSON serializers
    102122>>> json = serializers.serialize("json", Category.objects.filter(pk=2))
    103123>>> json
    104 '[{"pk": "2", "model": "serializers.category", "fields": {"name": "Music"}}]'
     124'[{"pk": 2, "model": "serializers.category", "fields": {"name": "Music"}}]'
    105125
    106126# You can easily create new objects by deserializing data with an empty PK
    107127# (It's easier to demo this with JSON...)
     
    133153
    134154>>> json = serializers.serialize("json", AuthorProfile.objects.all())
    135155>>> 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"}}]'
    137157
    138158>>> for obj in serializers.deserialize("json", json):
    139159...     print obj
     
    141161
    142162# Objects ids can be referenced before they are defined in the serialization data
    143163# 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"}}]'
    145165>>> from django.db import transaction
    146166>>> transaction.enter_transaction_management()
    147167>>> transaction.managed(True)
     
    161181
    162182# Serializer output can be restricted to a subset of fields
    163183>>> 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"}}]
    165185
     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
     198u'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
     208None
     209
    166210"""}
  • tests/modeltests/fixtures/models.py

     
    7474
    7575# Dump the current contents of the database as a JSON fixture
    7676>>> 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"}}]
    7878"""}
    7979
    8080from django.test import TestCase
Back to Top