serialization.txt 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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 "ships" with a few included serializers:
  90. ========== ==============================================================
  91. Identifier Information
  92. ========== ==============================================================
  93. ``xml`` Serializes to and from a simple XML dialect.
  94. ``json`` Serializes to and from JSON_ (using a version of simplejson_
  95. bundled with Django).
  96. ``python`` Translates to and from "simple" Python objects (lists, dicts,
  97. strings, etc.). Not really all that useful on its own, but
  98. used as a base for other serializers.
  99. ``yaml`` Serializes to YAML (YAML Ain't a Markup Language). This
  100. serializer is only available if PyYAML_ is installed.
  101. ========== ==============================================================
  102. .. _json: http://json.org/
  103. .. _simplejson: http://undefined.org/python/#simplejson
  104. .. _PyYAML: http://www.pyyaml.org/
  105. Notes for specific serialization formats
  106. ----------------------------------------
  107. json
  108. ~~~~
  109. If you're using UTF-8 (or any other non-ASCII encoding) data with the JSON
  110. serializer, you must pass ``ensure_ascii=False`` as a parameter to the
  111. ``serialize()`` call. Otherwise, the output won't be encoded correctly.
  112. For example::
  113. json_serializer = serializers.get_serializer("json")()
  114. json_serializer.serialize(queryset, ensure_ascii=False, stream=response)
  115. The Django source code includes the simplejson_ module. Be aware that if you're
  116. serializing using that module directly, not all Django output can be passed
  117. unmodified to simplejson. In particular, :ref:`lazy translation objects
  118. <lazy-translations>` need a `special encoder`_ written for them. Something like
  119. this will work::
  120. from django.utils.functional import Promise
  121. from django.utils.encoding import force_unicode
  122. class LazyEncoder(simplejson.JSONEncoder):
  123. def default(self, obj):
  124. if isinstance(obj, Promise):
  125. return force_unicode(obj)
  126. return obj
  127. .. _special encoder: http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.7/docs/index.html