Fixed #4653 -- Improved the logic to decide when to include (and select as
[django.git] / docs / serialization.txt
blobcf8b196931a75175fab5310b61035079b72280de
1 ==========================
2 Serializing Django objects
3 ==========================
5 .. note::
7     This API is currently under heavy development and may change --
8     perhaps drastically -- in the future.
10     You have been warned.
12 Django's serialization framework provides a mechanism for "translating" Django
13 objects into other formats. Usually these other formats will be text-based and
14 used for sending Django objects over a wire, but it's possible for a
15 serializer to handle any format (text-based or not).
17 Serializing data
18 ----------------
20 At the highest level, serializing data is a very simple operation::
22     from django.core import serializers
23     data = serializers.serialize("xml", SomeModel.objects.all())
25 The arguments to the ``serialize`` function are the format to serialize the
26 data to (see `Serialization formats`_) and a QuerySet_ to serialize.
27 (Actually, the second argument can be any iterator that yields Django objects,
28 but it'll almost always be a QuerySet).
30 .. _QuerySet: ../db-api/#retrieving-objects
32 You can also use a serializer object directly::
34     XMLSerializer = serializers.get_serializer("xml")
35     xml_serializer = XMLSerializer()
36     xml_serializer.serialize(queryset)
37     data = xml_serializer.getvalue()
39 This is useful if you want to serialize data directly to a file-like object
40 (which includes a HTTPResponse_)::
42     out = open("file.xml", "w")
43     xml_serializer.serialize(SomeModel.objects.all(), stream=out)
45 .. _HTTPResponse: ../request_response/#httpresponse-objects
47 Subset of fields
48 ~~~~~~~~~~~~~~~~
50 If you only want a subset of fields to be serialized, you can
51 specify a ``fields`` argument to the serializer::
53     from django.core import serializers
54     data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
56 In this example, only the ``name`` and ``size`` attributes of each model will
57 be serialized.
59 .. note::
61     Depending on your model, you may find that it is not possible to deserialize
62     a model that only serializes a subset of its fields. If a serialized object
63     doesn't specify all the fields that are required by a model, the deserializer
64     will not be able to save deserialized instances.
66 Deserializing data
67 ------------------
69 Deserializing data is also a fairly simple operation::
71     for obj in serializers.deserialize("xml", data):
72         do_something_with(obj)
74 As you can see, the ``deserialize`` function takes the same format argument as
75 ``serialize``, a string or stream of data, and returns an iterator.
77 However, here it gets slightly complicated. The objects returned by the
78 ``deserialize`` iterator *aren't* simple Django objects. Instead, they are
79 special ``DeserializedObject`` instances that wrap a created -- but unsaved --
80 object and any associated relationship data.
82 Calling ``DeserializedObject.save()`` saves the object to the database.
84 This ensures that deserializing is a non-destructive operation even if the
85 data in your serialized representation doesn't match what's currently in the
86 database. Usually, working with these ``DeserializedObject`` instances looks
87 something like::
89     for deserialized_object in serializers.deserialize("xml", data):
90         if object_should_be_saved(deserialized_object):
91             obj.save()
93 In other words, the usual use is to examine the deserialized objects to make
94 sure that they are "appropriate" for saving before doing so.  Of course, if you trust your data source you could just save the object and move on.
96 The Django object itself can be inspected as ``deserialized_object.object``.
98 Serialization formats
99 ---------------------
101 Django "ships" with a few included serializers:
103     ==========  ==============================================================
104     Identifier  Information
105     ==========  ==============================================================
106     ``xml``     Serializes to and from a simple XML dialect.
108     ``json``    Serializes to and from JSON_ (using a version of simplejson_
109                 bundled with Django).
111     ``python``  Translates to and from "simple" Python objects (lists, dicts,
112                 strings, etc.).  Not really all that useful on its own, but
113                 used as a base for other serializers.
115     ``yaml``    Serializes to YAML (Yet Another Markup Lanuage). This
116                 serializer is only available if PyYAML_ is installed.
117     ==========  ==============================================================
119 .. _json: http://json.org/
120 .. _simplejson: http://undefined.org/python/#simplejson
121 .. _PyYAML: http://www.pyyaml.org/
123 Notes for specific serialization formats
124 ----------------------------------------
126 json
127 ~~~~
129 If you're using UTF-8 (or any other non-ASCII encoding) data with the JSON
130 serializer, you must pass ``ensure_ascii=False`` as a parameter to the
131 ``serialize()`` call. Otherwise, the output won't be encoded correctly.
133 For example::
135     json_serializer = serializers.get_serializer("json")()
136     json_serializer.serialize(queryset, ensure_ascii=False, stream=response)
138 Django ships with a copy of simplejson_ in the source. Be aware, that if
139 you're using that for serializing directly that not all Django output can be
140 passed unmodified to simplejson. In particular, `lazy translation objects`_
141 need a `special encoder`_ written for them. Something like this will work::
143     from django.utils.functional import Promise
144     from django.utils.encoding import force_unicode
146     class LazyEncoder(simplejson.JSONEncoder):
147         def default(self, obj):
148             if isinstance(obj, Promise):
149                 return force_unicode(obj)
150             return obj
152 .. _lazy translation objects: ../i18n/#lazy-translation
153 .. _special encoder: http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.7/docs/index.html
155 Writing custom serializers
156 ``````````````````````````
158 XXX ...