2008-08-24 00:25:40 +02:00
|
|
|
.. _topics-serialization:
|
|
|
|
|
2006-06-28 18:00:37 +02:00
|
|
|
==========================
|
|
|
|
Serializing Django objects
|
|
|
|
==========================
|
|
|
|
|
|
|
|
Django's serialization framework provides a mechanism for "translating" Django
|
|
|
|
objects into other formats. Usually these other formats will be text-based and
|
|
|
|
used for sending Django objects over a wire, but it's possible for a
|
|
|
|
serializer to handle any format (text-based or not).
|
|
|
|
|
|
|
|
Serializing data
|
|
|
|
----------------
|
|
|
|
|
|
|
|
At the highest level, serializing data is a very simple operation::
|
|
|
|
|
|
|
|
from django.core import serializers
|
|
|
|
data = serializers.serialize("xml", SomeModel.objects.all())
|
2006-09-25 19:44:07 +02:00
|
|
|
|
2008-08-24 00:25:40 +02:00
|
|
|
The arguments to the ``serialize`` function are the format to serialize the data
|
|
|
|
to (see `Serialization formats`_) and a :class:`~django.db.models.QuerySet` to
|
|
|
|
serialize. (Actually, the second argument can be any iterator that yields Django
|
|
|
|
objects, but it'll almost always be a QuerySet).
|
2006-06-28 18:00:37 +02:00
|
|
|
|
|
|
|
You can also use a serializer object directly::
|
|
|
|
|
2007-03-22 13:54:23 +01:00
|
|
|
XMLSerializer = serializers.get_serializer("xml")
|
|
|
|
xml_serializer = XMLSerializer()
|
2006-06-28 18:00:37 +02:00
|
|
|
xml_serializer.serialize(queryset)
|
|
|
|
data = xml_serializer.getvalue()
|
2006-09-25 19:44:07 +02:00
|
|
|
|
2006-06-28 18:00:37 +02:00
|
|
|
This is useful if you want to serialize data directly to a file-like object
|
2008-11-01 21:14:36 +01:00
|
|
|
(which includes an :class:`~django.http.HttpResponse`)::
|
2006-06-28 18:00:37 +02:00
|
|
|
|
|
|
|
out = open("file.xml", "w")
|
|
|
|
xml_serializer.serialize(SomeModel.objects.all(), stream=out)
|
|
|
|
|
2007-06-01 15:39:08 +02:00
|
|
|
Subset of fields
|
|
|
|
~~~~~~~~~~~~~~~~
|
|
|
|
|
2007-11-04 03:08:24 +01:00
|
|
|
If you only want a subset of fields to be serialized, you can
|
2007-07-01 03:00:23 +02:00
|
|
|
specify a ``fields`` argument to the serializer::
|
2007-06-01 15:39:08 +02:00
|
|
|
|
|
|
|
from django.core import serializers
|
|
|
|
data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
|
|
|
|
|
2007-07-01 03:00:23 +02:00
|
|
|
In this example, only the ``name`` and ``size`` attributes of each model will
|
2007-11-04 03:08:24 +01:00
|
|
|
be serialized.
|
2007-06-01 15:39:08 +02:00
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2008-08-03 23:02:59 +02:00
|
|
|
Depending on your model, you may find that it is not possible to
|
|
|
|
deserialize a model that only serializes a subset of its fields. If a
|
|
|
|
serialized object doesn't specify all the fields that are required by a
|
|
|
|
model, the deserializer will not be able to save deserialized instances.
|
2007-06-01 15:39:08 +02:00
|
|
|
|
2008-06-09 16:03:35 +02:00
|
|
|
Inherited Models
|
|
|
|
~~~~~~~~~~~~~~~~
|
|
|
|
|
2008-09-03 22:23:18 +02:00
|
|
|
If you have a model that is defined using an :ref:`abstract base class
|
|
|
|
<abstract-base-classes>`, you don't have to do anything special to serialize
|
|
|
|
that model. Just call the serializer on the object (or objects) that you want to
|
|
|
|
serialize, and the output will be a complete representation of the serialized
|
|
|
|
object.
|
2008-06-09 16:03:35 +02:00
|
|
|
|
2008-09-03 22:23:18 +02:00
|
|
|
However, if you have a model that uses :ref:`multi-table inheritance
|
|
|
|
<multi-table-inheritance>`, you also need to serialize all of the base classes
|
|
|
|
for the model. This is because only the fields that are locally defined on the
|
|
|
|
model will be serialized. For example, consider the following models::
|
2008-08-03 23:02:59 +02:00
|
|
|
|
2008-09-03 22:23:18 +02:00
|
|
|
class Place(models.Model):
|
|
|
|
name = models.CharField(max_length=50)
|
2008-08-03 23:02:59 +02:00
|
|
|
|
2008-09-03 22:23:18 +02:00
|
|
|
class Restaurant(Place):
|
|
|
|
serves_hot_dogs = models.BooleanField()
|
2008-08-03 23:02:59 +02:00
|
|
|
|
2008-06-09 16:03:35 +02:00
|
|
|
If you only serialize the Restaurant model::
|
|
|
|
|
2008-09-03 22:23:18 +02:00
|
|
|
data = serializers.serialize('xml', Restaurant.objects.all())
|
2008-06-09 16:03:35 +02:00
|
|
|
|
|
|
|
the fields on the serialized output will only contain the `serves_hot_dogs`
|
|
|
|
attribute. The `name` attribute of the base class will be ignored.
|
|
|
|
|
|
|
|
In order to fully serialize your Restaurant instances, you will need to
|
|
|
|
serialize the Place models as well::
|
|
|
|
|
2008-09-03 22:23:18 +02:00
|
|
|
all_objects = list(Restaurant.objects.all()) + list(Place.objects.all())
|
|
|
|
data = serializers.serialize('xml', all_objects)
|
2008-06-09 16:03:35 +02:00
|
|
|
|
2006-06-28 18:00:37 +02:00
|
|
|
Deserializing data
|
|
|
|
------------------
|
|
|
|
|
|
|
|
Deserializing data is also a fairly simple operation::
|
|
|
|
|
|
|
|
for obj in serializers.deserialize("xml", data):
|
|
|
|
do_something_with(obj)
|
2006-09-25 19:44:07 +02:00
|
|
|
|
2006-06-28 18:00:37 +02:00
|
|
|
As you can see, the ``deserialize`` function takes the same format argument as
|
|
|
|
``serialize``, a string or stream of data, and returns an iterator.
|
|
|
|
|
|
|
|
However, here it gets slightly complicated. The objects returned by the
|
|
|
|
``deserialize`` iterator *aren't* simple Django objects. Instead, they are
|
|
|
|
special ``DeserializedObject`` instances that wrap a created -- but unsaved --
|
|
|
|
object and any associated relationship data.
|
|
|
|
|
|
|
|
Calling ``DeserializedObject.save()`` saves the object to the database.
|
|
|
|
|
|
|
|
This ensures that deserializing is a non-destructive operation even if the
|
|
|
|
data in your serialized representation doesn't match what's currently in the
|
|
|
|
database. Usually, working with these ``DeserializedObject`` instances looks
|
|
|
|
something like::
|
|
|
|
|
|
|
|
for deserialized_object in serializers.deserialize("xml", data):
|
|
|
|
if object_should_be_saved(deserialized_object):
|
2008-02-19 00:43:12 +01:00
|
|
|
deserialized_object.save()
|
2006-09-25 19:44:07 +02:00
|
|
|
|
2006-06-28 18:00:37 +02:00
|
|
|
In other words, the usual use is to examine the deserialized objects to make
|
2008-08-03 23:02:59 +02:00
|
|
|
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.
|
2006-06-28 18:00:37 +02:00
|
|
|
|
|
|
|
The Django object itself can be inspected as ``deserialized_object.object``.
|
|
|
|
|
2008-08-24 00:25:40 +02:00
|
|
|
.. _serialization-formats:
|
|
|
|
|
2006-06-28 18:00:37 +02:00
|
|
|
Serialization formats
|
|
|
|
---------------------
|
|
|
|
|
2009-02-21 09:40:07 +01:00
|
|
|
Django supports a number of serialization formats, some of which require you
|
|
|
|
to install third-party Python modules:
|
2006-06-28 18:00:37 +02:00
|
|
|
|
2006-06-29 18:42:49 +02:00
|
|
|
========== ==============================================================
|
|
|
|
Identifier Information
|
|
|
|
========== ==============================================================
|
|
|
|
``xml`` Serializes to and from a simple XML dialect.
|
|
|
|
|
|
|
|
``json`` Serializes to and from JSON_ (using a version of simplejson_
|
|
|
|
bundled with Django).
|
|
|
|
|
|
|
|
``python`` Translates to and from "simple" Python objects (lists, dicts,
|
2006-09-25 19:44:07 +02:00
|
|
|
strings, etc.). Not really all that useful on its own, but
|
2006-06-29 18:42:49 +02:00
|
|
|
used as a base for other serializers.
|
2007-11-04 03:08:24 +01:00
|
|
|
|
2008-05-24 07:15:21 +02:00
|
|
|
``yaml`` Serializes to YAML (YAML Ain't a Markup Language). This
|
2007-11-04 03:08:24 +01:00
|
|
|
serializer is only available if PyYAML_ is installed.
|
2006-06-29 18:42:49 +02:00
|
|
|
========== ==============================================================
|
|
|
|
|
|
|
|
.. _json: http://json.org/
|
|
|
|
.. _simplejson: http://undefined.org/python/#simplejson
|
2007-06-01 15:39:08 +02:00
|
|
|
.. _PyYAML: http://www.pyyaml.org/
|
2006-06-29 18:42:49 +02:00
|
|
|
|
2006-09-25 19:44:07 +02:00
|
|
|
Notes for specific serialization formats
|
2006-09-22 15:26:07 +02:00
|
|
|
----------------------------------------
|
|
|
|
|
|
|
|
json
|
|
|
|
~~~~
|
|
|
|
|
2006-09-25 19:44:07 +02:00
|
|
|
If you're using UTF-8 (or any other non-ASCII encoding) data with the JSON
|
2006-09-22 15:26:07 +02:00
|
|
|
serializer, you must pass ``ensure_ascii=False`` as a parameter to the
|
2006-09-25 19:44:07 +02:00
|
|
|
``serialize()`` call. Otherwise, the output won't be encoded correctly.
|
2006-09-22 15:26:07 +02:00
|
|
|
|
|
|
|
For example::
|
|
|
|
|
2007-05-08 05:07:58 +02:00
|
|
|
json_serializer = serializers.get_serializer("json")()
|
2006-09-22 15:26:07 +02:00
|
|
|
json_serializer.serialize(queryset, ensure_ascii=False, stream=response)
|
|
|
|
|
2009-01-06 06:13:02 +01:00
|
|
|
The Django source code includes the simplejson_ module. However, if you're
|
|
|
|
using Python 2.6 (which includes a builtin version of the module), Django will
|
|
|
|
use the builtin ``json`` module automatically. If you have a system installed
|
|
|
|
version that includes the C-based speedup extension, or your system version is
|
|
|
|
more recent than the version shipped with Django (currently, 2.0.7), the
|
|
|
|
system version will be used instead of the version included with Django.
|
|
|
|
|
|
|
|
Be aware that if you're serializing using that module directly, not all Django
|
|
|
|
output can be passed unmodified to simplejson. In particular, :ref:`lazy
|
|
|
|
translation objects <lazy-translations>` need a `special encoder`_ written for
|
|
|
|
them. Something like this will work::
|
2007-11-04 03:08:24 +01:00
|
|
|
|
|
|
|
from django.utils.functional import Promise
|
|
|
|
from django.utils.encoding import force_unicode
|
|
|
|
|
|
|
|
class LazyEncoder(simplejson.JSONEncoder):
|
|
|
|
def default(self, obj):
|
|
|
|
if isinstance(obj, Promise):
|
|
|
|
return force_unicode(obj)
|
|
|
|
return obj
|
|
|
|
|
|
|
|
.. _special encoder: http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.7/docs/index.html
|
2009-01-06 06:13:02 +01:00
|
|
|
|