serialization.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. .. function:: django.core.serializers.get_serializer(format)
  22. You can also use a serializer object directly::
  23. XMLSerializer = serializers.get_serializer("xml")
  24. xml_serializer = XMLSerializer()
  25. xml_serializer.serialize(queryset)
  26. data = xml_serializer.getvalue()
  27. This is useful if you want to serialize data directly to a file-like object
  28. (which includes an :class:`~django.http.HttpResponse`)::
  29. with open("file.xml", "w") as out:
  30. xml_serializer.serialize(SomeModel.objects.all(), stream=out)
  31. .. note::
  32. Calling :func:`~django.core.serializers.get_serializer` with an unknown
  33. :ref:`format <serialization-formats>` will raise a
  34. ``django.core.serializers.SerializerDoesNotExist`` exception.
  35. Subset of fields
  36. ~~~~~~~~~~~~~~~~
  37. If you only want a subset of fields to be serialized, you can
  38. specify a ``fields`` argument to the serializer::
  39. from django.core import serializers
  40. data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
  41. In this example, only the ``name`` and ``size`` attributes of each model will
  42. be serialized.
  43. .. note::
  44. Depending on your model, you may find that it is not possible to
  45. deserialize a model that only serializes a subset of its fields. If a
  46. serialized object doesn't specify all the fields that are required by a
  47. model, the deserializer will not be able to save deserialized instances.
  48. Inherited Models
  49. ~~~~~~~~~~~~~~~~
  50. If you have a model that is defined using an :ref:`abstract base class
  51. <abstract-base-classes>`, you don't have to do anything special to serialize
  52. that model. Just call the serializer on the object (or objects) that you want to
  53. serialize, and the output will be a complete representation of the serialized
  54. object.
  55. However, if you have a model that uses :ref:`multi-table inheritance
  56. <multi-table-inheritance>`, you also need to serialize all of the base classes
  57. for the model. This is because only the fields that are locally defined on the
  58. model will be serialized. For example, consider the following models::
  59. class Place(models.Model):
  60. name = models.CharField(max_length=50)
  61. class Restaurant(Place):
  62. serves_hot_dogs = models.BooleanField()
  63. If you only serialize the Restaurant model::
  64. data = serializers.serialize('xml', Restaurant.objects.all())
  65. the fields on the serialized output will only contain the ``serves_hot_dogs``
  66. attribute. The ``name`` attribute of the base class will be ignored.
  67. In order to fully serialize your ``Restaurant`` instances, you will need to
  68. serialize the ``Place`` models as well::
  69. all_objects = list(Restaurant.objects.all()) + list(Place.objects.all())
  70. data = serializers.serialize('xml', all_objects)
  71. Deserializing data
  72. ------------------
  73. Deserializing data is also a fairly simple operation::
  74. for obj in serializers.deserialize("xml", data):
  75. do_something_with(obj)
  76. As you can see, the ``deserialize`` function takes the same format argument as
  77. ``serialize``, a string or stream of data, and returns an iterator.
  78. However, here it gets slightly complicated. The objects returned by the
  79. ``deserialize`` iterator *aren't* simple Django objects. Instead, they are
  80. special ``DeserializedObject`` instances that wrap a created -- but unsaved --
  81. object and any associated relationship data.
  82. Calling ``DeserializedObject.save()`` saves the object to the database.
  83. .. note::
  84. If the ``pk`` attribute in the serialized data doesn't exist or is
  85. null, a new instance will be saved to the database.
  86. .. versionchanged:: 1.6
  87. In previous versions of Django, the ``pk`` attribute had to be present
  88. on the serialized data or a ``DeserializationError`` would be raised.
  89. This ensures that deserializing is a non-destructive operation even if the
  90. data in your serialized representation doesn't match what's currently in the
  91. database. Usually, working with these ``DeserializedObject`` instances looks
  92. something like::
  93. for deserialized_object in serializers.deserialize("xml", data):
  94. if object_should_be_saved(deserialized_object):
  95. deserialized_object.save()
  96. In other words, the usual use is to examine the deserialized objects to make
  97. sure that they are "appropriate" for saving before doing so. Of course, if you
  98. trust your data source you could just save the object and move on.
  99. The Django object itself can be inspected as ``deserialized_object.object``.
  100. .. versionadded:: 1.5
  101. If fields in the serialized data do not exist on a model,
  102. a ``DeserializationError`` will be raised unless the ``ignorenonexistent``
  103. argument is passed in as True::
  104. serializers.deserialize("xml", data, ignorenonexistent=True)
  105. .. _serialization-formats:
  106. Serialization formats
  107. ---------------------
  108. Django supports a number of serialization formats, some of which require you
  109. to install third-party Python modules:
  110. ========== ==============================================================
  111. Identifier Information
  112. ========== ==============================================================
  113. ``xml`` Serializes to and from a simple XML dialect.
  114. ``json`` Serializes to and from JSON_.
  115. ``yaml`` Serializes to YAML (YAML Ain't a Markup Language). This
  116. serializer is only available if PyYAML_ is installed.
  117. ========== ==============================================================
  118. .. _json: http://json.org/
  119. .. _PyYAML: http://www.pyyaml.org/
  120. XML
  121. ~~~
  122. The basic XML serialization format is quite simple::
  123. <?xml version="1.0" encoding="utf-8"?>
  124. <django-objects version="1.0">
  125. <object pk="123" model="sessions.session">
  126. <field type="DateTimeField" name="expire_date">2013-01-16T08:16:59.844560+00:00</field>
  127. <!-- ... -->
  128. </object>
  129. </django-objects>
  130. The whole collection of objects that is either serialized or de-serialized is
  131. represented by a ``<django-objects>``-tag which contains multiple
  132. ``<object>``-elements. Each such object has two attributes: "pk" and "model",
  133. the latter being represented by the name of the app ("sessions") and the
  134. lowercase name of the model ("session") separated by a dot.
  135. Each field of the object is serialized as a ``<field>``-element sporting the
  136. fields "type" and "name". The text content of the element represents the value
  137. that should be stored.
  138. Foreign keys and other relational fields are treated a little bit differently::
  139. <object pk="27" model="auth.permission">
  140. <!-- ... -->
  141. <field to="contenttypes.contenttype" name="content_type" rel="ManyToOneRel">9</field>
  142. <!-- ... -->
  143. </object>
  144. In this example we specify that the auth.Permission object with the PK 24 has
  145. a foreign key to the contenttypes.ContentType instance with the PK 9.
  146. ManyToMany-relations are exported for the model that binds them. For instance,
  147. the auth.User model has such a relation to the auth.Permission model::
  148. <object pk="1" model="auth.user">
  149. <!-- ... -->
  150. <field to="auth.permission" name="user_permissions" rel="ManyToManyRel">
  151. <object pk="46"></object>
  152. <object pk="47"></object>
  153. </field>
  154. </object>
  155. This example links the given user with the permission models with PKs 46 and 47.
  156. JSON
  157. ~~~~
  158. When staying with the same example data as before it would be serialized as
  159. JSON in the following way::
  160. [
  161. {
  162. "pk": "4b678b301dfd8a4e0dad910de3ae245b",
  163. "model": "sessions.session",
  164. "fields": {
  165. "expire_date": "2013-01-16T08:16:59.844Z",
  166. ...
  167. }
  168. }
  169. ]
  170. The formatting here is a bit simpler than with XML. The whole collection
  171. is just represented as an array and the objects are represented by JSON objects
  172. with three properties: "pk", "model" and "fields". "fields" is again an object
  173. containing each field's name and value as property and property-value
  174. respectively.
  175. Foreign keys just have the PK of the linked object as property value.
  176. ManyToMany-relations are serialized for the model that defines them and are
  177. represented as a list of PKs.
  178. Date and datetime related types are treated in a special way by the JSON
  179. serializer to make the format compatible with `ECMA-262`_.
  180. Be aware that not all Django output can be passed unmodified to :mod:`json`.
  181. In particular, :ref:`lazy translation objects <lazy-translations>` need a
  182. `special encoder`_ written for them. Something like this will work::
  183. import json
  184. from django.utils.functional import Promise
  185. from django.utils.encoding import force_text
  186. from django.core.serializers.json import DjangoJSONEncoder
  187. class LazyEncoder(DjangoJSONEncoder):
  188. def default(self, obj):
  189. if isinstance(obj, Promise):
  190. return force_text(obj)
  191. return super(LazyEncoder, self).default(obj)
  192. .. _special encoder: http://docs.python.org/library/json.html#encoders-and-decoders
  193. .. _ecma-262: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
  194. YAML
  195. ~~~~
  196. YAML serialization looks quite similar to JSON. The object list is serialized
  197. as a sequence mappings with the keys "pk", "model" and "fields". Each field is
  198. again a mapping with the key being name of the field and the value the value::
  199. - fields: {expire_date: !!timestamp '2013-01-16 08:16:59.844560+00:00'}
  200. model: sessions.session
  201. pk: 4b678b301dfd8a4e0dad910de3ae245b
  202. Referential fields are again just represented by the PK or sequence of PKs.
  203. .. _topics-serialization-natural-keys:
  204. Natural keys
  205. ------------
  206. The default serialization strategy for foreign keys and many-to-many relations
  207. is to serialize the value of the primary key(s) of the objects in the relation.
  208. This strategy works well for most objects, but it can cause difficulty in some
  209. circumstances.
  210. Consider the case of a list of objects that have a foreign key referencing
  211. :class:`~django.contrib.contenttypes.models.ContentType`. If you're going to
  212. serialize an object that refers to a content type, then you need to have a way
  213. to refer to that content type to begin with. Since ``ContentType`` objects are
  214. automatically created by Django during the database synchronization process,
  215. the primary key of a given content type isn't easy to predict; it will
  216. depend on how and when :djadmin:`syncdb` was executed. This is true for all
  217. models which automatically generate objects, notably including
  218. :class:`~django.contrib.auth.models.Permission`,
  219. :class:`~django.contrib.auth.models.Group`, and
  220. :class:`~django.contrib.auth.models.User`.
  221. .. warning::
  222. You should never include automatically generated objects in a fixture or
  223. other serialized data. By chance, the primary keys in the fixture
  224. may match those in the database and loading the fixture will
  225. have no effect. In the more likely case that they don't match, the fixture
  226. loading will fail with an :class:`~django.db.IntegrityError`.
  227. There is also the matter of convenience. An integer id isn't always
  228. the most convenient way to refer to an object; sometimes, a
  229. more natural reference would be helpful.
  230. It is for these reasons that Django provides *natural keys*. A natural
  231. key is a tuple of values that can be used to uniquely identify an
  232. object instance without using the primary key value.
  233. Deserialization of natural keys
  234. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  235. Consider the following two models::
  236. from django.db import models
  237. class Person(models.Model):
  238. first_name = models.CharField(max_length=100)
  239. last_name = models.CharField(max_length=100)
  240. birthdate = models.DateField()
  241. class Meta:
  242. unique_together = (('first_name', 'last_name'),)
  243. class Book(models.Model):
  244. name = models.CharField(max_length=100)
  245. author = models.ForeignKey(Person)
  246. Ordinarily, serialized data for ``Book`` would use an integer to refer to
  247. the author. For example, in JSON, a Book might be serialized as::
  248. ...
  249. {
  250. "pk": 1,
  251. "model": "store.book",
  252. "fields": {
  253. "name": "Mostly Harmless",
  254. "author": 42
  255. }
  256. }
  257. ...
  258. This isn't a particularly natural way to refer to an author. It
  259. requires that you know the primary key value for the author; it also
  260. requires that this primary key value is stable and predictable.
  261. However, if we add natural key handling to Person, the fixture becomes
  262. much more humane. To add natural key handling, you define a default
  263. Manager for Person with a ``get_by_natural_key()`` method. In the case
  264. of a Person, a good natural key might be the pair of first and last
  265. name::
  266. from django.db import models
  267. class PersonManager(models.Manager):
  268. def get_by_natural_key(self, first_name, last_name):
  269. return self.get(first_name=first_name, last_name=last_name)
  270. class Person(models.Model):
  271. objects = PersonManager()
  272. first_name = models.CharField(max_length=100)
  273. last_name = models.CharField(max_length=100)
  274. birthdate = models.DateField()
  275. class Meta:
  276. unique_together = (('first_name', 'last_name'),)
  277. Now books can use that natural key to refer to ``Person`` objects::
  278. ...
  279. {
  280. "pk": 1,
  281. "model": "store.book",
  282. "fields": {
  283. "name": "Mostly Harmless",
  284. "author": ["Douglas", "Adams"]
  285. }
  286. }
  287. ...
  288. When you try to load this serialized data, Django will use the
  289. ``get_by_natural_key()`` method to resolve ``["Douglas", "Adams"]``
  290. into the primary key of an actual ``Person`` object.
  291. .. note::
  292. Whatever fields you use for a natural key must be able to uniquely
  293. identify an object. This will usually mean that your model will
  294. have a uniqueness clause (either unique=True on a single field, or
  295. ``unique_together`` over multiple fields) for the field or fields
  296. in your natural key. However, uniqueness doesn't need to be
  297. enforced at the database level. If you are certain that a set of
  298. fields will be effectively unique, you can still use those fields
  299. as a natural key.
  300. Serialization of natural keys
  301. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  302. So how do you get Django to emit a natural key when serializing an object?
  303. Firstly, you need to add another method -- this time to the model itself::
  304. class Person(models.Model):
  305. objects = PersonManager()
  306. first_name = models.CharField(max_length=100)
  307. last_name = models.CharField(max_length=100)
  308. birthdate = models.DateField()
  309. def natural_key(self):
  310. return (self.first_name, self.last_name)
  311. class Meta:
  312. unique_together = (('first_name', 'last_name'),)
  313. That method should always return a natural key tuple -- in this
  314. example, ``(first name, last name)``. Then, when you call
  315. ``serializers.serialize()``, you provide a ``use_natural_keys=True``
  316. argument::
  317. >>> serializers.serialize('json', [book1, book2], indent=2, use_natural_keys=True)
  318. When ``use_natural_keys=True`` is specified, Django will use the
  319. ``natural_key()`` method to serialize any reference to objects of the
  320. type that defines the method.
  321. If you are using :djadmin:`dumpdata` to generate serialized data, you
  322. use the :djadminopt:`--natural` command line flag to generate natural keys.
  323. .. note::
  324. You don't need to define both ``natural_key()`` and
  325. ``get_by_natural_key()``. If you don't want Django to output
  326. natural keys during serialization, but you want to retain the
  327. ability to load natural keys, then you can opt to not implement
  328. the ``natural_key()`` method.
  329. Conversely, if (for some strange reason) you want Django to output
  330. natural keys during serialization, but *not* be able to load those
  331. key values, just don't define the ``get_by_natural_key()`` method.
  332. Dependencies during serialization
  333. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  334. Since natural keys rely on database lookups to resolve references, it
  335. is important that the data exists before it is referenced. You can't make
  336. a "forward reference" with natural keys -- the data you're referencing
  337. must exist before you include a natural key reference to that data.
  338. To accommodate this limitation, calls to :djadmin:`dumpdata` that use
  339. the :djadminopt:`--natural` option will serialize any model with a
  340. ``natural_key()`` method before serializing standard primary key objects.
  341. However, this may not always be enough. If your natural key refers to
  342. another object (by using a foreign key or natural key to another object
  343. as part of a natural key), then you need to be able to ensure that
  344. the objects on which a natural key depends occur in the serialized data
  345. before the natural key requires them.
  346. To control this ordering, you can define dependencies on your
  347. ``natural_key()`` methods. You do this by setting a ``dependencies``
  348. attribute on the ``natural_key()`` method itself.
  349. For example, let's add a natural key to the ``Book`` model from the
  350. example above::
  351. class Book(models.Model):
  352. name = models.CharField(max_length=100)
  353. author = models.ForeignKey(Person)
  354. def natural_key(self):
  355. return (self.name,) + self.author.natural_key()
  356. The natural key for a ``Book`` is a combination of its name and its
  357. author. This means that ``Person`` must be serialized before ``Book``.
  358. To define this dependency, we add one extra line::
  359. def natural_key(self):
  360. return (self.name,) + self.author.natural_key()
  361. natural_key.dependencies = ['example_app.person']
  362. This definition ensures that all ``Person`` objects are serialized before
  363. any ``Book`` objects. In turn, any object referencing ``Book`` will be
  364. serialized after both ``Person`` and ``Book`` have been serialized.