Django

Code

Changeset 6645

Show
Ignore:
Timestamp:
11/03/07 21:08:24 (1 year ago)
Author:
mtredinnick
Message:

Fixed #5868 -- Provided an example of how to extend simplejson to serialize
lazy translation objects for those who want to use it directly.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/docs/serialization.txt

    r5571 r6645  
    4848~~~~~~~~~~~~~~~~ 
    4949 
    50 If you only want a subset of fields to be serialized, you can  
     50If you only want a subset of fields to be serialized, you can 
    5151specify a ``fields`` argument to the serializer:: 
    5252 
     
    5555 
    5656In this example, only the ``name`` and ``size`` attributes of each model will 
    57 be serialized.  
     57be serialized. 
    5858 
    5959.. note:: 
     
    112112                strings, etc.).  Not really all that useful on its own, but 
    113113                used as a base for other serializers. 
    114      
    115     ``yaml``    Serializes to YAML (Yet Another Markup Lanuage). This  
    116                 serializer is only available if PyYAML_ is installed.  
     114 
     115    ``yaml``    Serializes to YAML (Yet Another Markup Lanuage). This 
     116                serializer is only available if PyYAML_ is installed. 
    117117    ==========  ============================================================== 
    118118 
     
    136136    json_serializer.serialize(queryset, ensure_ascii=False, stream=response) 
    137137 
     138Django ships with a copy of simplejson_ in the source. Be aware, that if 
     139you're using that for serializing directly that not all Django output can be 
     140passed unmodified to simplejson. In particular, `lazy translation objects`_ 
     141need a `special encoder`_ written for them. Something like this will work:: 
     142 
     143    from django.utils.functional import Promise 
     144    from django.utils.encoding import force_unicode 
     145 
     146    class LazyEncoder(simplejson.JSONEncoder): 
     147        def default(self, obj): 
     148            if isinstance(obj, Promise): 
     149                return force_unicode(obj) 
     150            return obj 
     151 
     152.. _lazy translation objects: ../i18n/#lazy-translation 
     153.. _special encoder: http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.7/docs/index.html 
     154 
    138155Writing custom serializers 
    139156``````````````````````````