serialization.txt 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. .. _topics-serialization:
  2. ==========================
  3. Serializing Django objects
  4. ==========================
  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).
  9. .. seealso::
  10. If you just want to get some data from your tables into a serialized
  11. form, you could use the :djadmin:`dumpdata` management command.
  12. Serializing data
  13. ----------------
  14. 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())
  17. The arguments to the ``serialize`` function are the format to serialize the data
  18. to (see `Serialization formats`_) and a :class:`~django.db.models.QuerySet` to
  19. serialize. (Actually, the second argument can be any iterator that yields Django
  20. objects, but it'll 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. out = open("file.xml", "w")
  29. xml_serializer.serialize(SomeModel.objects.all(), stream=out)
  30. Subset of fields
  31. ~~~~~~~~~~~~~~~~
  32. If you only want a subset of fields to be serialized, you can
  33. specify a ``fields`` argument to the serializer::
  34. from django.core import serializers
  35. data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
  36. In this example, only the ``name`` and ``size`` attributes of each model will
  37. be serialized.
  38. .. note::
  39. Depending on your model, you may find that it is not possible to
  40. deserialize a model that only serializes a subset of its fields. If a
  41. serialized object doesn't specify all the fields that are required by a
  42. model, the deserializer will not be able to save deserialized instances.
  43. Inherited Models
  44. ~~~~~~~~~~~~~~~~
  45. If you have a model that is defined using an :ref:`abstract base class
  46. <abstract-base-classes>`, you don't have to do anything special to serialize
  47. that model. Just call the serializer on the object (or objects) that you want to
  48. serialize, and the output will be a complete representation of the serialized
  49. object.
  50. However, if you have a model that uses :ref:`multi-table inheritance
  51. <multi-table-inheritance>`, you also need to serialize all of the base classes
  52. for the model. This is because only the fields that are locally defined on the
  53. model will be serialized. For example, consider the following models::
  54. class Place(models.Model):
  55. name = models.CharField(max_length=50)
  56. class Restaurant(Place):
  57. serves_hot_dogs = models.BooleanField()
  58. If you only serialize the Restaurant model::
  59. data = serializers.serialize('xml', Restaurant.objects.all())
  60. the fields on the serialized output will only contain the `serves_hot_dogs`
  61. attribute. The `name` attribute of the base class will be ignored.
  62. In order to fully serialize your Restaurant instances, you will need to
  63. serialize the Place models as well::
  64. all_objects = list(Restaurant.objects.all()) + list(Place.objects.all())
  65. data = serializers.serialize('xml', all_objects)
  66. Deserializing data
  67. ------------------
  68. Deserializing data is also a fairly simple operation::
  69. for obj in serializers.deserialize("xml", data):
  70. do_something_with(obj)
  71. As you can see, the ``deserialize`` function takes the same format argument as
  72. ``serialize``, a string or stream of data, and returns an iterator.
  73. However, here it gets slightly complicated. The objects returned by the
  74. ``deserialize`` iterator *aren't* simple Django objects. Instead, they are
  75. special ``DeserializedObject`` instances that wrap a created -- but unsaved --
  76. object and any associated relationship data.
  77. Calling ``DeserializedObject.save()`` saves the object to the database.
  78. This ensures that deserializing is a non-destructive operation even if the
  79. data in your serialized representation doesn't match what's currently in the
  80. database. Usually, working with these ``DeserializedObject`` instances looks
  81. something like::
  82. for deserialized_object in serializers.deserialize("xml", data):
  83. if object_should_be_saved(deserialized_object):
  84. deserialized_object.save()
  85. In other words, the usual use is to examine the deserialized objects to make
  86. sure that they are "appropriate" for saving before doing so. Of course, if you
  87. trust your data source you could just save the object and move on.
  88. The Django object itself can be inspected as ``deserialized_object.object``.
  89. .. _serialization-formats:
  90. Serialization formats
  91. ---------------------
  92. Django supports a number of serialization formats, some of which require you
  93. to install third-party Python modules:
  94. ========== ==============================================================
  95. Identifier Information
  96. ========== ==============================================================
  97. ``xml`` Serializes to and from a simple XML dialect.
  98. ``json`` Serializes to and from JSON_ (using a version of simplejson_
  99. bundled with Django).
  100. ``python`` Translates to and from "simple" Python objects (lists, dicts,
  101. strings, etc.). Not really all that useful on its own, but
  102. used as a base for other serializers.
  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. .. _simplejson: http://undefined.org/python/#simplejson
  108. .. _PyYAML: http://www.pyyaml.org/
  109. Notes for specific serialization formats
  110. ----------------------------------------
  111. json
  112. ~~~~
  113. If you're using UTF-8 (or any other non-ASCII encoding) data with the JSON
  114. serializer, you must pass ``ensure_ascii=False`` as a parameter to the
  115. ``serialize()`` call. Otherwise, the output won't be encoded correctly.
  116. For example::
  117. json_serializer = serializers.get_serializer("json")()
  118. json_serializer.serialize(queryset, ensure_ascii=False, stream=response)
  119. The Django source code includes the simplejson_ module. However, if you're
  120. using Python 2.6 (which includes a builtin version of the module), Django will
  121. use the builtin ``json`` module automatically. If you have a system installed
  122. version that includes the C-based speedup extension, or your system version is
  123. more recent than the version shipped with Django (currently, 2.0.7), the
  124. system version will be used instead of the version included with Django.
  125. Be aware that if you're serializing using that module directly, not all Django
  126. output can be passed unmodified to simplejson. In particular, :ref:`lazy
  127. translation objects <lazy-translations>` need a `special encoder`_ written for
  128. them. Something like this will work::
  129. from django.utils.functional import Promise
  130. from django.utils.encoding import force_unicode
  131. class LazyEncoder(simplejson.JSONEncoder):
  132. def default(self, obj):
  133. if isinstance(obj, Promise):
  134. return force_unicode(obj)
  135. return super(LazyEncoder, self).default(obj)
  136. .. _special encoder: http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.7/docs/index.html