Fixed #8267: Corrected documentation for default value of DEFAULT_FILE_STORAGE setting
[django.git] / docs / serialization.txt
blob971103747ca382293f7fd0b76bcb82edaad1ab86
1 ==========================
2 Serializing Django objects
3 ==========================
5 Django's serialization framework provides a mechanism for "translating" Django
6 objects into other formats. Usually these other formats will be text-based and
7 used for sending Django objects over a wire, but it's possible for a
8 serializer to handle any format (text-based or not).
10 Serializing data
11 ----------------
13 At the highest level, serializing data is a very simple operation::
15     from django.core import serializers
16     data = serializers.serialize("xml", SomeModel.objects.all())
18 The arguments to the ``serialize`` function are the format to serialize the
19 data to (see `Serialization formats`_) and a QuerySet_ to serialize.
20 (Actually, the second argument can be any iterator that yields Django objects,
21 but it'll almost always be a QuerySet).
23 .. _QuerySet: ../db-api/#retrieving-objects
25 You can also use a serializer object directly::
27     XMLSerializer = serializers.get_serializer("xml")
28     xml_serializer = XMLSerializer()
29     xml_serializer.serialize(queryset)
30     data = xml_serializer.getvalue()
32 This is useful if you want to serialize data directly to a file-like object
33 (which includes a HTTPResponse_)::
35     out = open("file.xml", "w")
36     xml_serializer.serialize(SomeModel.objects.all(), stream=out)
38 .. _HTTPResponse: ../request_response/#httpresponse-objects
40 Subset of fields
41 ~~~~~~~~~~~~~~~~
43 If you only want a subset of fields to be serialized, you can
44 specify a ``fields`` argument to the serializer::
46     from django.core import serializers
47     data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
49 In this example, only the ``name`` and ``size`` attributes of each model will
50 be serialized.
52 .. note::
54     Depending on your model, you may find that it is not possible to
55     deserialize a model that only serializes a subset of its fields. If a
56     serialized object doesn't specify all the fields that are required by a
57     model, the deserializer will not be able to save deserialized instances.
59 Inherited Models
60 ~~~~~~~~~~~~~~~~
62 If you have a model that is defined using an `abstract base class`_, you don't
63 have to do anything special to serialize that model. Just call the serializer
64 on the object (or objects) that you want to serialize, and the output will be
65 a complete representation of the serialized object.
67 However, if you have a model that uses `multi-table inheritance`_, you also
68 need to serialize all of the base classes for the model. This is because only
69 the fields that are locally defined on the model will be serialized. For
70 example, consider the following models::
72         class Place(models.Model):
73                 name = models.CharField(max_length=50)
75         class Restaurant(Place):
76                 serves_hot_dogs = models.BooleanField()
78 If you only serialize the Restaurant model::
80         data = serializers.serialize('xml', Restaurant.objects.all())
82 the fields on the serialized output will only contain the `serves_hot_dogs`
83 attribute. The `name` attribute of the base class will be ignored.
85 In order to fully serialize your Restaurant instances, you will need to
86 serialize the Place models as well::
88         all_objects = list(Restaurant.objects.all()) + list(Place.objects.all())
89         data = serializers.serialize('xml', all_objects)
91 .. _abstract base class: http://www.djangoproject.com/documentation/model-api/#abstract-base-classes
92 .. _multi-table inheritance: http://www.djangoproject.com/documentation/model-api/#multi-table-inheritance
94 Deserializing data
95 ------------------
97 Deserializing data is also a fairly simple operation::
99     for obj in serializers.deserialize("xml", data):
100         do_something_with(obj)
102 As you can see, the ``deserialize`` function takes the same format argument as
103 ``serialize``, a string or stream of data, and returns an iterator.
105 However, here it gets slightly complicated. The objects returned by the
106 ``deserialize`` iterator *aren't* simple Django objects. Instead, they are
107 special ``DeserializedObject`` instances that wrap a created -- but unsaved --
108 object and any associated relationship data.
110 Calling ``DeserializedObject.save()`` saves the object to the database.
112 This ensures that deserializing is a non-destructive operation even if the
113 data in your serialized representation doesn't match what's currently in the
114 database. Usually, working with these ``DeserializedObject`` instances looks
115 something like::
117     for deserialized_object in serializers.deserialize("xml", data):
118         if object_should_be_saved(deserialized_object):
119             deserialized_object.save()
121 In other words, the usual use is to examine the deserialized objects to make
122 sure that they are "appropriate" for saving before doing so.  Of course, if you
123 trust your data source you could just save the object and move on.
125 The Django object itself can be inspected as ``deserialized_object.object``.
127 Serialization formats
128 ---------------------
130 Django "ships" with a few included serializers:
132     ==========  ==============================================================
133     Identifier  Information
134     ==========  ==============================================================
135     ``xml``     Serializes to and from a simple XML dialect.
137     ``json``    Serializes to and from JSON_ (using a version of simplejson_
138                 bundled with Django).
140     ``python``  Translates to and from "simple" Python objects (lists, dicts,
141                 strings, etc.).  Not really all that useful on its own, but
142                 used as a base for other serializers.
144     ``yaml``    Serializes to YAML (YAML Ain't a Markup Language). This
145                 serializer is only available if PyYAML_ is installed.
146     ==========  ==============================================================
148 .. _json: http://json.org/
149 .. _simplejson: http://undefined.org/python/#simplejson
150 .. _PyYAML: http://www.pyyaml.org/
152 Notes for specific serialization formats
153 ----------------------------------------
155 json
156 ~~~~
158 If you're using UTF-8 (or any other non-ASCII encoding) data with the JSON
159 serializer, you must pass ``ensure_ascii=False`` as a parameter to the
160 ``serialize()`` call. Otherwise, the output won't be encoded correctly.
162 For example::
164     json_serializer = serializers.get_serializer("json")()
165     json_serializer.serialize(queryset, ensure_ascii=False, stream=response)
167 The Django source code includes the simplejson_ module. Be aware that if
168 you're serializing using that module directly, not all Django output can be
169 passed unmodified to simplejson. In particular, `lazy translation objects`_
170 need a `special encoder`_ written for them. Something like this will work::
172     from django.utils.functional import Promise
173     from django.utils.encoding import force_unicode
175     class LazyEncoder(simplejson.JSONEncoder):
176         def default(self, obj):
177             if isinstance(obj, Promise):
178                 return force_unicode(obj)
179             return obj
181 .. _lazy translation objects: ../i18n/#lazy-translation
182 .. _special encoder: http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.7/docs/index.html