serialization.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. ==========================
  2. Serializing Django objects
  3. ==========================
  4. Django's serialization framework provides a mechanism for "translating" Django
  5. models into other formats. Usually these other formats will be text-based and
  6. used for sending Django data over a wire, but it's possible for a
  7. serializer to handle any format (text-based or not).
  8. .. seealso::
  9. If you just want to get some data from your tables into a serialized
  10. form, you could use the :djadmin:`dumpdata` management command.
  11. Serializing data
  12. ----------------
  13. At the highest level, serializing data is a very simple operation::
  14. from django.core import serializers
  15. data = serializers.serialize("xml", SomeModel.objects.all())
  16. The arguments to the ``serialize`` function are the format to serialize the data
  17. to (see `Serialization formats`_) and a
  18. :class:`~django.db.models.query.QuerySet` to serialize. (Actually, the second
  19. argument can be any iterator that yields Django model instances, but it'll
  20. almost always be a QuerySet).
  21. You can also use a serializer object directly::
  22. XMLSerializer = serializers.get_serializer("xml")
  23. xml_serializer = XMLSerializer()
  24. xml_serializer.serialize(queryset)
  25. data = xml_serializer.getvalue()
  26. This is useful if you want to serialize data directly to a file-like object
  27. (which includes an :class:`~django.http.HttpResponse`)::
  28. with open("file.xml", "w") as out:
  29. xml_serializer.serialize(SomeModel.objects.all(), stream=out)
  30. .. note::
  31. Calling :func:`~django.core.serializers.get_serializer` with an unknown
  32. :ref:`format <serialization-formats>` will raise a
  33. :class:`~django.core.serializers.SerializerDoesNotExist` exception.
  34. Subset of fields
  35. ~~~~~~~~~~~~~~~~
  36. If you only want a subset of fields to be serialized, you can
  37. specify a ``fields`` argument to the serializer::
  38. from django.core import serializers
  39. data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
  40. In this example, only the ``name`` and ``size`` attributes of each model will
  41. be serialized.
  42. .. note::
  43. Depending on your model, you may find that it is not possible to
  44. deserialize a model that only serializes a subset of its fields. If a
  45. serialized object doesn't specify all the fields that are required by a
  46. model, the deserializer will not be able to save deserialized instances.
  47. Inherited Models
  48. ~~~~~~~~~~~~~~~~
  49. If you have a model that is defined using an :ref:`abstract base class
  50. <abstract-base-classes>`, you don't have to do anything special to serialize
  51. that model. Just call the serializer on the object (or objects) that you want to
  52. serialize, and the output will be a complete representation of the serialized
  53. object.
  54. However, if you have a model that uses :ref:`multi-table inheritance
  55. <multi-table-inheritance>`, you also need to serialize all of the base classes
  56. for the model. This is because only the fields that are locally defined on the
  57. model will be serialized. For example, consider the following models::
  58. class Place(models.Model):
  59. name = models.CharField(max_length=50)
  60. class Restaurant(Place):
  61. serves_hot_dogs = models.BooleanField()
  62. If you only serialize the Restaurant model::
  63. data = serializers.serialize('xml', Restaurant.objects.all())
  64. the fields on the serialized output will only contain the `serves_hot_dogs`
  65. attribute. The `name` attribute of the base class will be ignored.
  66. In order to fully serialize your Restaurant instances, you will need to
  67. serialize the Place models as well::
  68. all_objects = list(Restaurant.objects.all()) + list(Place.objects.all())
  69. data = serializers.serialize('xml', all_objects)
  70. Deserializing data
  71. ------------------
  72. Deserializing data is also a fairly simple operation::
  73. for obj in serializers.deserialize("xml", data):
  74. do_something_with(obj)
  75. As you can see, the ``deserialize`` function takes the same format argument as
  76. ``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.
  81. Calling ``DeserializedObject.save()`` saves the object to the database.
  82. This ensures that deserializing is a non-destructive operation even if the
  83. data in your serialized representation doesn't match what's currently in the
  84. database. Usually, working with these ``DeserializedObject`` instances looks
  85. something like::
  86. for deserialized_object in serializers.deserialize("xml", data):
  87. if object_should_be_saved(deserialized_object):
  88. deserialized_object.save()
  89. In other words, the usual use is to examine the deserialized objects to make
  90. sure that they are "appropriate" for saving before doing so. Of course, if you
  91. trust your data source you could just save the object and move on.
  92. The Django object itself can be inspected as ``deserialized_object.object``.
  93. .. _serialization-formats:
  94. Serialization formats
  95. ---------------------
  96. Django supports a number of serialization formats, some of which require you
  97. to install third-party Python modules:
  98. ========== ==============================================================
  99. Identifier Information
  100. ========== ==============================================================
  101. ``xml`` Serializes to and from a simple XML dialect.
  102. ``json`` Serializes to and from JSON_.
  103. ``yaml`` Serializes to YAML (YAML Ain't a Markup Language). This
  104. serializer is only available if PyYAML_ is installed.
  105. ========== ==============================================================
  106. .. _json: http://json.org/
  107. .. _PyYAML: http://www.pyyaml.org/
  108. Notes for specific serialization formats
  109. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  110. json
  111. ^^^^
  112. If you're using UTF-8 (or any other non-ASCII encoding) data with the JSON
  113. serializer, you must pass ``ensure_ascii=False`` as a parameter to the
  114. ``serialize()`` call. Otherwise, the output won't be encoded correctly.
  115. For example::
  116. json_serializer = serializers.get_serializer("json")()
  117. json_serializer.serialize(queryset, ensure_ascii=False, stream=response)
  118. Be aware that not all Django output can be passed unmodified to :mod:`json`.
  119. In particular, :ref:`lazy translation objects <lazy-translations>` need a
  120. `special encoder`_ written for them. Something like this will work::
  121. import json
  122. from django.utils.functional import Promise
  123. from django.utils.encoding import force_unicode
  124. class LazyEncoder(json.JSONEncoder):
  125. def default(self, obj):
  126. if isinstance(obj, Promise):
  127. return force_unicode(obj)
  128. return super(LazyEncoder, self).default(obj)
  129. .. _special encoder: http://docs.python.org/library/json.html#encoders-and-decoders
  130. .. _topics-serialization-natural-keys:
  131. Natural keys
  132. ------------
  133. .. versionadded:: 1.2
  134. The ability to use natural keys when serializing/deserializing data was
  135. added in the 1.2 release.
  136. The default serialization strategy for foreign keys and many-to-many relations
  137. is to serialize the value of the primary key(s) of the objects in the relation.
  138. This strategy works well for most objects, but it can cause difficulty in some
  139. circumstances.
  140. Consider the case of a list of objects that have a foreign key referencing
  141. :class:`~django.contrib.conttenttypes.models.ContentType`. If you're going to
  142. serialize an object that refers to a content type, then you need to have a way
  143. to refer to that content type to begin with. Since ``ContentType`` objects are
  144. automatically created by Django during the database synchronization process,
  145. the primary key of a given content type isn't easy to predict; it will
  146. depend on how and when :djadmin:`syncdb` was executed. This is true for all
  147. models which automatically generate objects, notably including
  148. :class:`~django.contrib.auth.models.Permission`,
  149. :class:`~django.contrib.auth.models.Group`, and
  150. :class:`~django.contrib.auth.models.User`.
  151. .. warning::
  152. You should never include automatically generated objects in a fixture or
  153. other serialized data. By chance, the primary keys in the fixture
  154. may match those in the database and loading the fixture will
  155. have no effect. In the more likely case that they don't match, the fixture
  156. loading will fail with an :class:`~django.db.IntegrityError`.
  157. There is also the matter of convenience. An integer id isn't always
  158. the most convenient way to refer to an object; sometimes, a
  159. more natural reference would be helpful.
  160. It is for these reasons that Django provides *natural keys*. A natural
  161. key is a tuple of values that can be used to uniquely identify an
  162. object instance without using the primary key value.
  163. Deserialization of natural keys
  164. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  165. Consider the following two models::
  166. from django.db import models
  167. class Person(models.Model):
  168. first_name = models.CharField(max_length=100)
  169. last_name = models.CharField(max_length=100)
  170. birthdate = models.DateField()
  171. class Meta:
  172. unique_together = (('first_name', 'last_name'),)
  173. class Book(models.Model):
  174. name = models.CharField(max_length=100)
  175. author = models.ForeignKey(Person)
  176. Ordinarily, serialized data for ``Book`` would use an integer to refer to
  177. the author. For example, in JSON, a Book might be serialized as::
  178. ...
  179. {
  180. "pk": 1,
  181. "model": "store.book",
  182. "fields": {
  183. "name": "Mostly Harmless",
  184. "author": 42
  185. }
  186. }
  187. ...
  188. This isn't a particularly natural way to refer to an author. It
  189. requires that you know the primary key value for the author; it also
  190. requires that this primary key value is stable and predictable.
  191. However, if we add natural key handling to Person, the fixture becomes
  192. much more humane. To add natural key handling, you define a default
  193. Manager for Person with a ``get_by_natural_key()`` method. In the case
  194. of a Person, a good natural key might be the pair of first and last
  195. name::
  196. from django.db import models
  197. class PersonManager(models.Manager):
  198. def get_by_natural_key(self, first_name, last_name):
  199. return self.get(first_name=first_name, last_name=last_name)
  200. class Person(models.Model):
  201. objects = PersonManager()
  202. first_name = models.CharField(max_length=100)
  203. last_name = models.CharField(max_length=100)
  204. birthdate = models.DateField()
  205. class Meta:
  206. unique_together = (('first_name', 'last_name'),)
  207. Now books can use that natural key to refer to ``Person`` objects::
  208. ...
  209. {
  210. "pk": 1,
  211. "model": "store.book",
  212. "fields": {
  213. "name": "Mostly Harmless",
  214. "author": ["Douglas", "Adams"]
  215. }
  216. }
  217. ...
  218. When you try to load this serialized data, Django will use the
  219. ``get_by_natural_key()`` method to resolve ``["Douglas", "Adams"]``
  220. into the primary key of an actual ``Person`` object.
  221. .. note::
  222. Whatever fields you use for a natural key must be able to uniquely
  223. identify an object. This will usually mean that your model will
  224. have a uniqueness clause (either unique=True on a single field, or
  225. ``unique_together`` over multiple fields) for the field or fields
  226. in your natural key. However, uniqueness doesn't need to be
  227. enforced at the database level. If you are certain that a set of
  228. fields will be effectively unique, you can still use those fields
  229. as a natural key.
  230. Serialization of natural keys
  231. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  232. So how do you get Django to emit a natural key when serializing an object?
  233. Firstly, you need to add another method -- this time to the model itself::
  234. class Person(models.Model):
  235. objects = PersonManager()
  236. first_name = models.CharField(max_length=100)
  237. last_name = models.CharField(max_length=100)
  238. birthdate = models.DateField()
  239. def natural_key(self):
  240. return (self.first_name, self.last_name)
  241. class Meta:
  242. unique_together = (('first_name', 'last_name'),)
  243. That method should always return a natural key tuple -- in this
  244. example, ``(first name, last name)``. Then, when you call
  245. ``serializers.serialize()``, you provide a ``use_natural_keys=True``
  246. argument::
  247. >>> serializers.serialize('json', [book1, book2], indent=2, use_natural_keys=True)
  248. When ``use_natural_keys=True`` is specified, Django will use the
  249. ``natural_key()`` method to serialize any reference to objects of the
  250. type that defines the method.
  251. If you are using :djadmin:`dumpdata` to generate serialized data, you
  252. use the `--natural` command line flag to generate natural keys.
  253. .. note::
  254. You don't need to define both ``natural_key()`` and
  255. ``get_by_natural_key()``. If you don't want Django to output
  256. natural keys during serialization, but you want to retain the
  257. ability to load natural keys, then you can opt to not implement
  258. the ``natural_key()`` method.
  259. Conversely, if (for some strange reason) you want Django to output
  260. natural keys during serialization, but *not* be able to load those
  261. key values, just don't define the ``get_by_natural_key()`` method.
  262. Dependencies during serialization
  263. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  264. Since natural keys rely on database lookups to resolve references, it
  265. is important that the data exists before it is referenced. You can't make
  266. a `forward reference` with natural keys -- the data you're referencing
  267. must exist before you include a natural key reference to that data.
  268. To accommodate this limitation, calls to :djadmin:`dumpdata` that use
  269. the :djadminopt:`--natural` option will serialize any model with a
  270. ``natural_key()`` method before serializing standard primary key objects.
  271. However, this may not always be enough. If your natural key refers to
  272. another object (by using a foreign key or natural key to another object
  273. as part of a natural key), then you need to be able to ensure that
  274. the objects on which a natural key depends occur in the serialized data
  275. before the natural key requires them.
  276. To control this ordering, you can define dependencies on your
  277. ``natural_key()`` methods. You do this by setting a ``dependencies``
  278. attribute on the ``natural_key()`` method itself.
  279. For example, let's add a natural key to the ``Book`` model from the
  280. example above::
  281. class Book(models.Model):
  282. name = models.CharField(max_length=100)
  283. author = models.ForeignKey(Person)
  284. def natural_key(self):
  285. return (self.name,) + self.author.natural_key()
  286. The natural key for a ``Book`` is a combination of its name and its
  287. author. This means that ``Person`` must be serialized before ``Book``.
  288. To define this dependency, we add one extra line::
  289. def natural_key(self):
  290. return (self.name,) + self.author.natural_key()
  291. natural_key.dependencies = ['example_app.person']
  292. This definition ensures that all ``Person`` objects are serialized before
  293. any ``Book`` objects. In turn, any object referencing ``Book`` will be
  294. serialized after both ``Person`` and ``Book`` have been serialized.