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).
|
|
|
|
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 20:30:54 +02:00
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
If you just want to get some data from your tables into a serialized
|
|
|
|
form, you could use the :djadmin:`dumpdata` management command.
|
|
|
|
|
2006-06-28 18:00:37 +02:00
|
|
|
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
|
2009-12-14 13:39:20 +01:00
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2006-09-22 15:26:07 +02:00
|
|
|
|
|
|
|
json
|
2009-12-14 13:39:20 +01:00
|
|
|
^^^^
|
2006-09-22 15:26:07 +02:00
|
|
|
|
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)
|
2009-05-02 09:39:45 +02:00
|
|
|
return super(LazyEncoder, self).default(obj)
|
2007-11-04 03:08:24 +01:00
|
|
|
|
|
|
|
.. _special encoder: http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.7/docs/index.html
|
2009-01-06 06:13:02 +01:00
|
|
|
|
2009-12-14 13:39:20 +01:00
|
|
|
.. _topics-serialization-natural-keys:
|
|
|
|
|
|
|
|
Natural keys
|
|
|
|
------------
|
|
|
|
|
2010-02-14 19:39:42 +01:00
|
|
|
.. versionadded:: 1.2
|
|
|
|
The ability to use natural keys when serializing/deserializing data was
|
|
|
|
added in the 1.2 release.
|
|
|
|
|
2009-12-14 13:39:20 +01:00
|
|
|
The default serialization strategy for foreign keys and many-to-many
|
|
|
|
relations is to serialize the value of the primary key(s) of the
|
|
|
|
objects in the relation. This strategy works well for most types of
|
|
|
|
object, but it can cause difficulty in some circumstances.
|
|
|
|
|
|
|
|
Consider the case of a list of objects that have foreign key on
|
|
|
|
:class:`ContentType`. If you're going to serialize an object that
|
|
|
|
refers to a content type, you need to have a way to refer to that
|
|
|
|
content type. Content Types are automatically created by Django as
|
|
|
|
part of the database synchronization process, so you don't need to
|
|
|
|
include content types in a fixture or other serialized data. As a
|
|
|
|
result, the primary key of any given content type isn't easy to
|
|
|
|
predict - it will depend on how and when :djadmin:`syncdb` was
|
|
|
|
executed to create the content types.
|
|
|
|
|
|
|
|
There is also the matter of convenience. An integer id isn't always
|
|
|
|
the most convenient way to refer to an object; sometimes, a
|
|
|
|
more natural reference would be helpful.
|
|
|
|
|
|
|
|
Deserialization of natural keys
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
It is for these reasons that Django provides `natural keys`. A natural
|
|
|
|
key is a tuple of values that can be used to uniquely identify an
|
|
|
|
object instance without using the primary key value.
|
|
|
|
|
|
|
|
Consider the following two models::
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
first_name = models.CharField(max_length=100)
|
|
|
|
last_name = models.CharField(max_length=100)
|
|
|
|
|
|
|
|
birthdate = models.DateField()
|
|
|
|
|
|
|
|
class Book(models.Model):
|
|
|
|
name = models.CharField(max_length=100)
|
|
|
|
author = models.ForeignKey(Person)
|
|
|
|
|
|
|
|
Ordinarily, serialized data for ``Book`` would use an integer to refer to
|
|
|
|
the author. For example, in JSON, a Book might be serialized as::
|
|
|
|
|
|
|
|
...
|
|
|
|
{
|
|
|
|
"pk": 1,
|
|
|
|
"model": "store.book",
|
|
|
|
"fields": {
|
|
|
|
"name": "Mostly Harmless",
|
|
|
|
"author": 42
|
|
|
|
}
|
|
|
|
}
|
|
|
|
...
|
|
|
|
|
|
|
|
This isn't a particularly natural way to refer to an author. It
|
|
|
|
requires that you know the primary key value for the author; it also
|
|
|
|
requires that this primary key value is stable and predictable.
|
|
|
|
|
|
|
|
However, if we add natural key handling to Person, the fixture becomes
|
|
|
|
much more humane. To add natural key handling, you define a default
|
|
|
|
Manager for Person with a ``get_by_natural_key()`` method. In the case
|
|
|
|
of a Person, a good natural key might be the pair of first and last
|
|
|
|
name::
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class PersonManager(models.Manager):
|
|
|
|
def get_by_natural_key(self, first_name, last_name):
|
2009-12-18 01:32:10 +01:00
|
|
|
return self.get(first_name=first_name, last_name=last_name)
|
2009-12-14 13:39:20 +01:00
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
objects = PersonManager()
|
|
|
|
|
|
|
|
first_name = models.CharField(max_length=100)
|
|
|
|
last_name = models.CharField(max_length=100)
|
|
|
|
|
|
|
|
birthdate = models.DateField()
|
|
|
|
|
|
|
|
Now books can use that natural key to refer to ``Person`` objects::
|
|
|
|
|
|
|
|
...
|
|
|
|
{
|
|
|
|
"pk": 1,
|
|
|
|
"model": "store.book",
|
|
|
|
"fields": {
|
|
|
|
"name": "Mostly Harmless",
|
|
|
|
"author": ["Douglas", "Adams"]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
...
|
|
|
|
|
|
|
|
When you try to load this serialized data, Django will use the
|
|
|
|
``get_by_natural_key()`` method to resolve ``["Douglas", "Adams"]``
|
|
|
|
into the primary key of an actual ``Person`` object.
|
|
|
|
|
|
|
|
Serialization of natural keys
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
So how do you get Django to emit a natural key when serializing an object?
|
|
|
|
Firstly, you need to add another method -- this time to the model itself::
|
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
objects = PersonManager()
|
|
|
|
|
|
|
|
first_name = models.CharField(max_length=100)
|
|
|
|
last_name = models.CharField(max_length=100)
|
|
|
|
|
|
|
|
birthdate = models.DateField()
|
|
|
|
|
|
|
|
def natural_key(self):
|
|
|
|
return (self.first_name, self.last_name)
|
|
|
|
|
|
|
|
Then, when you call ``serializers.serialize()``, you provide a
|
|
|
|
``use_natural_keys=True`` argument::
|
|
|
|
|
|
|
|
>>> serializers.serialize([book1, book2], format='json', indent=2, use_natural_keys=True)
|
|
|
|
|
|
|
|
When ``use_natural_keys=True`` is specified, Django will use the
|
|
|
|
``natural_key()`` method to serialize any reference to objects of the
|
|
|
|
type that defines the method.
|
|
|
|
|
|
|
|
If you are using :djadmin:`dumpdata` to generate serialized data, you
|
|
|
|
use the `--natural` command line flag to generate natural keys.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
You don't need to define both ``natural_key()`` and
|
|
|
|
``get_by_natural_key()``. If you don't want Django to output
|
|
|
|
natural keys during serialization, but you want to retain the
|
|
|
|
ability to load natural keys, then you can opt to not implement
|
|
|
|
the ``natural_key()`` method.
|
|
|
|
|
|
|
|
Conversely, if (for some strange reason) you want Django to output
|
|
|
|
natural keys during serialization, but *not* be able to load those
|
|
|
|
key values, just don't define the ``get_by_natural_key()`` method.
|
|
|
|
|
|
|
|
Dependencies during serialization
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
Since natural keys rely on database lookups to resolve references, it
|
|
|
|
is important that data exists before it is referenced. You can't make
|
|
|
|
a `forward reference` with natural keys - the data you are referencing
|
|
|
|
must exist before you include a natural key reference to that data.
|
|
|
|
|
|
|
|
To accommodate this limitation, calls to :djadmin:`dumpdata` that use
|
2010-02-14 19:39:42 +01:00
|
|
|
the :djadminopt:`--natural` option will serialize any model with a
|
2009-12-14 13:39:20 +01:00
|
|
|
``natural_key()`` method before it serializes normal key objects.
|
|
|
|
|
|
|
|
However, this may not always be enough. If your natural key refers to
|
|
|
|
another object (by using a foreign key or natural key to another object
|
|
|
|
as part of a natural key), then you need to be able to ensure that
|
|
|
|
the objects on which a natural key depends occur in the serialized data
|
|
|
|
before the natural key requires them.
|
|
|
|
|
|
|
|
To control this ordering, you can define dependencies on your
|
|
|
|
``natural_key()`` methods. You do this by setting a ``dependencies``
|
|
|
|
attribute on the ``natural_key()`` method itself.
|
|
|
|
|
|
|
|
For example, consider the ``Permission`` model in ``contrib.auth``.
|
|
|
|
The following is a simplified version of the ``Permission`` model::
|
|
|
|
|
|
|
|
class Permission(models.Model):
|
|
|
|
name = models.CharField(max_length=50)
|
|
|
|
content_type = models.ForeignKey(ContentType)
|
|
|
|
codename = models.CharField(max_length=100)
|
|
|
|
# ...
|
|
|
|
def natural_key(self):
|
|
|
|
return (self.codename,) + self.content_type.natural_key()
|
|
|
|
|
|
|
|
The natural key for a ``Permission`` is a combination of the codename for the
|
|
|
|
``Permission``, and the ``ContentType`` to which the ``Permission`` applies. This means
|
|
|
|
that ``ContentType`` must be serialized before ``Permission``. To define this
|
|
|
|
dependency, we add one extra line::
|
|
|
|
|
|
|
|
class Permission(models.Model):
|
|
|
|
# ...
|
|
|
|
def natural_key(self):
|
|
|
|
return (self.codename,) + self.content_type.natural_key()
|
|
|
|
natural_key.dependencies = ['contenttypes.contenttype']
|
|
|
|
|
|
|
|
This definition ensures that ``ContentType`` models are serialized before
|
|
|
|
``Permission`` models. In turn, any object referencing ``Permission`` will
|
|
|
|
be serialized after both ``ContentType`` and ``Permission``.
|