serialization.txt 7.2 KB

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