1. ==========================
    
  2. Serializing Django objects
    
  3. ==========================
    
  4. 
    
  5. Django's serialization framework provides a mechanism for "translating" Django
    
  6. models into other formats. Usually these other formats will be text-based and
    
  7. used for sending Django data over a wire, but it's possible for a
    
  8. serializer to handle any format (text-based or not).
    
  9. 
    
  10. .. seealso::
    
  11. 
    
  12.     If you just want to get some data from your tables into a serialized
    
  13.     form, you could use the :djadmin:`dumpdata` management command.
    
  14. 
    
  15. Serializing data
    
  16. ================
    
  17. 
    
  18. At the highest level, you can serialize data like this::
    
  19. 
    
  20.     from django.core import serializers
    
  21.     data = serializers.serialize("xml", SomeModel.objects.all())
    
  22. 
    
  23. The arguments to the ``serialize`` function are the format to serialize the data
    
  24. to (see `Serialization formats`_) and a
    
  25. :class:`~django.db.models.query.QuerySet` to serialize. (Actually, the second
    
  26. argument can be any iterator that yields Django model instances, but it'll
    
  27. almost always be a QuerySet).
    
  28. 
    
  29. .. function:: django.core.serializers.get_serializer(format)
    
  30. 
    
  31. You can also use a serializer object directly::
    
  32. 
    
  33.     XMLSerializer = serializers.get_serializer("xml")
    
  34.     xml_serializer = XMLSerializer()
    
  35.     xml_serializer.serialize(queryset)
    
  36.     data = xml_serializer.getvalue()
    
  37. 
    
  38. This is useful if you want to serialize data directly to a file-like object
    
  39. (which includes an :class:`~django.http.HttpResponse`)::
    
  40. 
    
  41.     with open("file.xml", "w") as out:
    
  42.         xml_serializer.serialize(SomeModel.objects.all(), stream=out)
    
  43. 
    
  44. .. note::
    
  45. 
    
  46.     Calling :func:`~django.core.serializers.get_serializer` with an unknown
    
  47.     :ref:`format <serialization-formats>` will raise a
    
  48.     ``django.core.serializers.SerializerDoesNotExist`` exception.
    
  49. 
    
  50. .. _subset-of-fields:
    
  51. 
    
  52. Subset of fields
    
  53. ----------------
    
  54. 
    
  55. If you only want a subset of fields to be serialized, you can
    
  56. specify a ``fields`` argument to the serializer::
    
  57. 
    
  58.     from django.core import serializers
    
  59.     data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
    
  60. 
    
  61. In this example, only the ``name`` and ``size`` attributes of each model will
    
  62. be serialized. The primary key is always serialized as the ``pk`` element in the
    
  63. resulting output; it never appears in the ``fields`` part.
    
  64. 
    
  65. .. note::
    
  66. 
    
  67.     Depending on your model, you may find that it is not possible to
    
  68.     deserialize a model that only serializes a subset of its fields. If a
    
  69.     serialized object doesn't specify all the fields that are required by a
    
  70.     model, the deserializer will not be able to save deserialized instances.
    
  71. 
    
  72. Inherited models
    
  73. ----------------
    
  74. 
    
  75. If you have a model that is defined using an :ref:`abstract base class
    
  76. <abstract-base-classes>`, you don't have to do anything special to serialize
    
  77. that model. Call the serializer on the object (or objects) that you want to
    
  78. serialize, and the output will be a complete representation of the serialized
    
  79. object.
    
  80. 
    
  81. However, if you have a model that uses :ref:`multi-table inheritance
    
  82. <multi-table-inheritance>`, you also need to serialize all of the base classes
    
  83. for the model. This is because only the fields that are locally defined on the
    
  84. model will be serialized. For example, consider the following models::
    
  85. 
    
  86.     class Place(models.Model):
    
  87.         name = models.CharField(max_length=50)
    
  88. 
    
  89.     class Restaurant(Place):
    
  90.         serves_hot_dogs = models.BooleanField(default=False)
    
  91. 
    
  92. If you only serialize the Restaurant model::
    
  93. 
    
  94.     data = serializers.serialize('xml', Restaurant.objects.all())
    
  95. 
    
  96. the fields on the serialized output will only contain the ``serves_hot_dogs``
    
  97. attribute. The ``name`` attribute of the base class will be ignored.
    
  98. 
    
  99. In order to fully serialize your ``Restaurant`` instances, you will need to
    
  100. serialize the ``Place`` models as well::
    
  101. 
    
  102.     all_objects = [*Restaurant.objects.all(), *Place.objects.all()]
    
  103.     data = serializers.serialize('xml', all_objects)
    
  104. 
    
  105. Deserializing data
    
  106. ==================
    
  107. 
    
  108. Deserializing data is very similar to serializing it::
    
  109. 
    
  110.     for obj in serializers.deserialize("xml", data):
    
  111.         do_something_with(obj)
    
  112. 
    
  113. As you can see, the ``deserialize`` function takes the same format argument as
    
  114. ``serialize``, a string or stream of data, and returns an iterator.
    
  115. 
    
  116. However, here it gets slightly complicated. The objects returned by the
    
  117. ``deserialize`` iterator *aren't* regular Django objects. Instead, they are
    
  118. special ``DeserializedObject`` instances that wrap a created -- but unsaved --
    
  119. object and any associated relationship data.
    
  120. 
    
  121. Calling ``DeserializedObject.save()`` saves the object to the database.
    
  122. 
    
  123. .. note::
    
  124. 
    
  125.     If the ``pk`` attribute in the serialized data doesn't exist or is
    
  126.     null, a new instance will be saved to the database.
    
  127. 
    
  128. This ensures that deserializing is a non-destructive operation even if the
    
  129. data in your serialized representation doesn't match what's currently in the
    
  130. database. Usually, working with these ``DeserializedObject`` instances looks
    
  131. something like::
    
  132. 
    
  133.     for deserialized_object in serializers.deserialize("xml", data):
    
  134.         if object_should_be_saved(deserialized_object):
    
  135.             deserialized_object.save()
    
  136. 
    
  137. In other words, the usual use is to examine the deserialized objects to make
    
  138. sure that they are "appropriate" for saving before doing so. If you trust your
    
  139. data source you can instead save the object directly and move on.
    
  140. 
    
  141. The Django object itself can be inspected as ``deserialized_object.object``.
    
  142. If fields in the serialized data do not exist on a model, a
    
  143. ``DeserializationError`` will be raised unless the ``ignorenonexistent``
    
  144. argument is passed in as ``True``::
    
  145. 
    
  146.     serializers.deserialize("xml", data, ignorenonexistent=True)
    
  147. 
    
  148. .. _serialization-formats:
    
  149. 
    
  150. Serialization formats
    
  151. =====================
    
  152. 
    
  153. Django supports a number of serialization formats, some of which require you
    
  154. to install third-party Python modules:
    
  155. 
    
  156. ==========  ==============================================================
    
  157. Identifier  Information
    
  158. ==========  ==============================================================
    
  159. ``xml``     Serializes to and from a simple XML dialect.
    
  160. 
    
  161. ``json``    Serializes to and from JSON_.
    
  162. 
    
  163. ``jsonl``   Serializes to and from JSONL_.
    
  164. 
    
  165. ``yaml``    Serializes to YAML (YAML Ain't a Markup Language). This
    
  166.             serializer is only available if PyYAML_ is installed.
    
  167. ==========  ==============================================================
    
  168. 
    
  169. .. _json: https://json.org/
    
  170. .. _jsonl: https://jsonlines.org/
    
  171. .. _PyYAML: https://pyyaml.org/
    
  172. 
    
  173. XML
    
  174. ---
    
  175. 
    
  176. The basic XML serialization format looks like this::
    
  177. 
    
  178.     <?xml version="1.0" encoding="utf-8"?>
    
  179.     <django-objects version="1.0">
    
  180.         <object pk="123" model="sessions.session">
    
  181.             <field type="DateTimeField" name="expire_date">2013-01-16T08:16:59.844560+00:00</field>
    
  182.             <!-- ... -->
    
  183.         </object>
    
  184.     </django-objects>
    
  185. 
    
  186. The whole collection of objects that is either serialized or deserialized is
    
  187. represented by a ``<django-objects>``-tag which contains multiple
    
  188. ``<object>``-elements. Each such object has two attributes: "pk" and "model",
    
  189. the latter being represented by the name of the app ("sessions") and the
    
  190. lowercase name of the model ("session") separated by a dot.
    
  191. 
    
  192. Each field of the object is serialized as a ``<field>``-element sporting the
    
  193. fields "type" and "name". The text content of the element represents the value
    
  194. that should be stored.
    
  195. 
    
  196. Foreign keys and other relational fields are treated a little bit differently::
    
  197. 
    
  198.     <object pk="27" model="auth.permission">
    
  199.         <!-- ... -->
    
  200.         <field to="contenttypes.contenttype" name="content_type" rel="ManyToOneRel">9</field>
    
  201.         <!-- ... -->
    
  202.     </object>
    
  203. 
    
  204. In this example we specify that the ``auth.Permission`` object with the PK 27
    
  205. has a foreign key to the ``contenttypes.ContentType`` instance with the PK 9.
    
  206. 
    
  207. ManyToMany-relations are exported for the model that binds them. For instance,
    
  208. the ``auth.User`` model has such a relation to the ``auth.Permission`` model::
    
  209. 
    
  210.     <object pk="1" model="auth.user">
    
  211.         <!-- ... -->
    
  212.         <field to="auth.permission" name="user_permissions" rel="ManyToManyRel">
    
  213.             <object pk="46"></object>
    
  214.             <object pk="47"></object>
    
  215.         </field>
    
  216.     </object>
    
  217. 
    
  218. This example links the given user with the permission models with PKs 46 and 47.
    
  219. 
    
  220. .. admonition:: Control characters
    
  221. 
    
  222.     If the content to be serialized contains control characters that are not
    
  223.     accepted in the XML 1.0 standard, the serialization will fail with a
    
  224.     :exc:`ValueError` exception. Read also the W3C's explanation of `HTML,
    
  225.     XHTML, XML and Control Codes
    
  226.     <https://www.w3.org/International/questions/qa-controls>`_.
    
  227. 
    
  228. .. _serialization-formats-json:
    
  229. 
    
  230. JSON
    
  231. ----
    
  232. 
    
  233. When staying with the same example data as before it would be serialized as
    
  234. JSON in the following way::
    
  235. 
    
  236.     [
    
  237.         {
    
  238.             "pk": "4b678b301dfd8a4e0dad910de3ae245b",
    
  239.             "model": "sessions.session",
    
  240.             "fields": {
    
  241.                 "expire_date": "2013-01-16T08:16:59.844Z",
    
  242.                 ...
    
  243.             }
    
  244.         }
    
  245.     ]
    
  246. 
    
  247. The formatting here is a bit simpler than with XML. The whole collection
    
  248. is just represented as an array and the objects are represented by JSON objects
    
  249. with three properties: "pk", "model" and "fields". "fields" is again an object
    
  250. containing each field's name and value as property and property-value
    
  251. respectively.
    
  252. 
    
  253. Foreign keys have the PK of the linked object as property value.
    
  254. ManyToMany-relations are serialized for the model that defines them and are
    
  255. represented as a list of PKs.
    
  256. 
    
  257. Be aware that not all Django output can be passed unmodified to :mod:`json`.
    
  258. For example, if you have some custom type in an object to be serialized, you'll
    
  259. have to write a custom :mod:`json` encoder for it. Something like this will
    
  260. work::
    
  261. 
    
  262.     from django.core.serializers.json import DjangoJSONEncoder
    
  263. 
    
  264.     class LazyEncoder(DjangoJSONEncoder):
    
  265.         def default(self, obj):
    
  266.             if isinstance(obj, YourCustomType):
    
  267.                 return str(obj)
    
  268.             return super().default(obj)
    
  269. 
    
  270. You can then pass ``cls=LazyEncoder`` to the ``serializers.serialize()``
    
  271. function::
    
  272. 
    
  273.     from django.core.serializers import serialize
    
  274. 
    
  275.     serialize('json', SomeModel.objects.all(), cls=LazyEncoder)
    
  276. 
    
  277. Also note that GeoDjango provides a :doc:`customized GeoJSON serializer
    
  278. </ref/contrib/gis/serializers>`.
    
  279. 
    
  280. ``DjangoJSONEncoder``
    
  281. ~~~~~~~~~~~~~~~~~~~~~
    
  282. 
    
  283. .. class:: django.core.serializers.json.DjangoJSONEncoder
    
  284. 
    
  285. The JSON serializer uses ``DjangoJSONEncoder`` for encoding. A subclass of
    
  286. :class:`~json.JSONEncoder`, it handles these additional types:
    
  287. 
    
  288. :class:`~datetime.datetime`
    
  289.    A string of the form ``YYYY-MM-DDTHH:mm:ss.sssZ`` or
    
  290.    ``YYYY-MM-DDTHH:mm:ss.sss+HH:MM`` as defined in `ECMA-262`_.
    
  291. 
    
  292. :class:`~datetime.date`
    
  293.    A string of the form ``YYYY-MM-DD`` as defined in `ECMA-262`_.
    
  294. 
    
  295. :class:`~datetime.time`
    
  296.    A string of the form ``HH:MM:ss.sss`` as defined in `ECMA-262`_.
    
  297. 
    
  298. :class:`~datetime.timedelta`
    
  299.    A string representing a duration as defined in ISO-8601. For example,
    
  300.    ``timedelta(days=1, hours=2, seconds=3.4)`` is represented as
    
  301.    ``'P1DT02H00M03.400000S'``.
    
  302. 
    
  303. :class:`~decimal.Decimal`, ``Promise`` (``django.utils.functional.lazy()`` objects), :class:`~uuid.UUID`
    
  304.    A string representation of the object.
    
  305. 
    
  306. .. _ecma-262: https://262.ecma-international.org/5.1/#sec-15.9.1.15
    
  307. 
    
  308. .. _serialization-formats-jsonl:
    
  309. 
    
  310. JSONL
    
  311. -----
    
  312. 
    
  313. *JSONL* stands for *JSON Lines*. With this format, objects are separated by new
    
  314. lines, and each line contains a valid JSON object. JSONL serialized data looks
    
  315. like this::
    
  316. 
    
  317.     {"pk": "4b678b301dfd8a4e0dad910de3ae245b", "model": "sessions.session", "fields": {...}}
    
  318.     {"pk": "88bea72c02274f3c9bf1cb2bb8cee4fc", "model": "sessions.session", "fields": {...}}
    
  319.     {"pk": "9cf0e26691b64147a67e2a9f06ad7a53", "model": "sessions.session", "fields": {...}}
    
  320. 
    
  321. JSONL can be useful for populating large databases, since the data can be
    
  322. processed line by line, rather than being loaded into memory all at once.
    
  323. 
    
  324. YAML
    
  325. ----
    
  326. 
    
  327. YAML serialization looks quite similar to JSON. The object list is serialized
    
  328. as a sequence mappings with the keys "pk", "model" and "fields". Each field is
    
  329. again a mapping with the key being name of the field and the value the value::
    
  330. 
    
  331.     - model: sessions.session
    
  332.       pk: 4b678b301dfd8a4e0dad910de3ae245b
    
  333.       fields:
    
  334.         expire_date: 2013-01-16 08:16:59.844560+00:00
    
  335. 
    
  336. Referential fields are again represented by the PK or sequence of PKs.
    
  337. 
    
  338. .. _topics-serialization-natural-keys:
    
  339. 
    
  340. Natural keys
    
  341. ============
    
  342. 
    
  343. The default serialization strategy for foreign keys and many-to-many relations
    
  344. is to serialize the value of the primary key(s) of the objects in the relation.
    
  345. This strategy works well for most objects, but it can cause difficulty in some
    
  346. circumstances.
    
  347. 
    
  348. Consider the case of a list of objects that have a foreign key referencing
    
  349. :class:`~django.contrib.contenttypes.models.ContentType`. If you're going to
    
  350. serialize an object that refers to a content type, then you need to have a way
    
  351. to refer to that content type to begin with. Since ``ContentType`` objects are
    
  352. automatically created by Django during the database synchronization process,
    
  353. the primary key of a given content type isn't easy to predict; it will
    
  354. depend on how and when :djadmin:`migrate` was executed. This is true for all
    
  355. models which automatically generate objects, notably including
    
  356. :class:`~django.contrib.auth.models.Permission`,
    
  357. :class:`~django.contrib.auth.models.Group`, and
    
  358. :class:`~django.contrib.auth.models.User`.
    
  359. 
    
  360. .. warning::
    
  361. 
    
  362.     You should never include automatically generated objects in a fixture or
    
  363.     other serialized data. By chance, the primary keys in the fixture
    
  364.     may match those in the database and loading the fixture will
    
  365.     have no effect. In the more likely case that they don't match, the fixture
    
  366.     loading will fail with an :class:`~django.db.IntegrityError`.
    
  367. 
    
  368. There is also the matter of convenience. An integer id isn't always
    
  369. the most convenient way to refer to an object; sometimes, a
    
  370. more natural reference would be helpful.
    
  371. 
    
  372. It is for these reasons that Django provides *natural keys*. A natural
    
  373. key is a tuple of values that can be used to uniquely identify an
    
  374. object instance without using the primary key value.
    
  375. 
    
  376. Deserialization of natural keys
    
  377. -------------------------------
    
  378. 
    
  379. Consider the following two models::
    
  380. 
    
  381.     from django.db import models
    
  382. 
    
  383.     class Person(models.Model):
    
  384.         first_name = models.CharField(max_length=100)
    
  385.         last_name = models.CharField(max_length=100)
    
  386. 
    
  387.         birthdate = models.DateField()
    
  388. 
    
  389.         class Meta:
    
  390.             unique_together = [['first_name', 'last_name']]
    
  391. 
    
  392.     class Book(models.Model):
    
  393.         name = models.CharField(max_length=100)
    
  394.         author = models.ForeignKey(Person, on_delete=models.CASCADE)
    
  395. 
    
  396. Ordinarily, serialized data for ``Book`` would use an integer to refer to
    
  397. the author. For example, in JSON, a Book might be serialized as::
    
  398. 
    
  399.     ...
    
  400.     {
    
  401.         "pk": 1,
    
  402.         "model": "store.book",
    
  403.         "fields": {
    
  404.             "name": "Mostly Harmless",
    
  405.             "author": 42
    
  406.         }
    
  407.     }
    
  408.     ...
    
  409. 
    
  410. This isn't a particularly natural way to refer to an author. It
    
  411. requires that you know the primary key value for the author; it also
    
  412. requires that this primary key value is stable and predictable.
    
  413. 
    
  414. However, if we add natural key handling to Person, the fixture becomes
    
  415. much more humane. To add natural key handling, you define a default
    
  416. Manager for Person with a ``get_by_natural_key()`` method. In the case
    
  417. of a Person, a good natural key might be the pair of first and last
    
  418. name::
    
  419. 
    
  420.     from django.db import models
    
  421. 
    
  422.     class PersonManager(models.Manager):
    
  423.         def get_by_natural_key(self, first_name, last_name):
    
  424.             return self.get(first_name=first_name, last_name=last_name)
    
  425. 
    
  426.     class Person(models.Model):
    
  427.         first_name = models.CharField(max_length=100)
    
  428.         last_name = models.CharField(max_length=100)
    
  429.         birthdate = models.DateField()
    
  430. 
    
  431.         objects = PersonManager()
    
  432. 
    
  433.         class Meta:
    
  434.             unique_together = [['first_name', 'last_name']]
    
  435. 
    
  436. Now books can use that natural key to refer to ``Person`` objects::
    
  437. 
    
  438.     ...
    
  439.     {
    
  440.         "pk": 1,
    
  441.         "model": "store.book",
    
  442.         "fields": {
    
  443.             "name": "Mostly Harmless",
    
  444.             "author": ["Douglas", "Adams"]
    
  445.         }
    
  446.     }
    
  447.     ...
    
  448. 
    
  449. When you try to load this serialized data, Django will use the
    
  450. ``get_by_natural_key()`` method to resolve ``["Douglas", "Adams"]``
    
  451. into the primary key of an actual ``Person`` object.
    
  452. 
    
  453. .. note::
    
  454. 
    
  455.     Whatever fields you use for a natural key must be able to uniquely
    
  456.     identify an object. This will usually mean that your model will
    
  457.     have a uniqueness clause (either unique=True on a single field, or
    
  458.     ``unique_together`` over multiple fields) for the field or fields
    
  459.     in your natural key. However, uniqueness doesn't need to be
    
  460.     enforced at the database level. If you are certain that a set of
    
  461.     fields will be effectively unique, you can still use those fields
    
  462.     as a natural key.
    
  463. 
    
  464. Deserialization of objects with no primary key will always check whether the
    
  465. model's manager has a ``get_by_natural_key()`` method and if so, use it to
    
  466. populate the deserialized object's primary key.
    
  467. 
    
  468. Serialization of natural keys
    
  469. -----------------------------
    
  470. 
    
  471. So how do you get Django to emit a natural key when serializing an object?
    
  472. Firstly, you need to add another method -- this time to the model itself::
    
  473. 
    
  474.     class Person(models.Model):
    
  475.         first_name = models.CharField(max_length=100)
    
  476.         last_name = models.CharField(max_length=100)
    
  477.         birthdate = models.DateField()
    
  478. 
    
  479.         objects = PersonManager()
    
  480. 
    
  481.         class Meta:
    
  482.             unique_together = [['first_name', 'last_name']]
    
  483. 
    
  484.         def natural_key(self):
    
  485.             return (self.first_name, self.last_name)
    
  486. 
    
  487. That method should always return a natural key tuple -- in this
    
  488. example, ``(first name, last name)``. Then, when you call
    
  489. ``serializers.serialize()``, you provide ``use_natural_foreign_keys=True``
    
  490. or ``use_natural_primary_keys=True`` arguments::
    
  491. 
    
  492.     >>> serializers.serialize('json', [book1, book2], indent=2,
    
  493.     ...      use_natural_foreign_keys=True, use_natural_primary_keys=True)
    
  494. 
    
  495. When ``use_natural_foreign_keys=True`` is specified, Django will use the
    
  496. ``natural_key()`` method to serialize any foreign key reference to objects
    
  497. of the type that defines the method.
    
  498. 
    
  499. When ``use_natural_primary_keys=True`` is specified, Django will not provide the
    
  500. primary key in the serialized data of this object since it can be calculated
    
  501. during deserialization::
    
  502. 
    
  503.     ...
    
  504.     {
    
  505.         "model": "store.person",
    
  506.         "fields": {
    
  507.             "first_name": "Douglas",
    
  508.             "last_name": "Adams",
    
  509.             "birth_date": "1952-03-11",
    
  510.         }
    
  511.     }
    
  512.     ...
    
  513. 
    
  514. This can be useful when you need to load serialized data into an existing
    
  515. database and you cannot guarantee that the serialized primary key value is not
    
  516. already in use, and do not need to ensure that deserialized objects retain the
    
  517. same primary keys.
    
  518. 
    
  519. If you are using :djadmin:`dumpdata` to generate serialized data, use the
    
  520. :option:`dumpdata --natural-foreign` and :option:`dumpdata --natural-primary`
    
  521. command line flags to generate natural keys.
    
  522. 
    
  523. .. note::
    
  524. 
    
  525.     You don't need to define both ``natural_key()`` and
    
  526.     ``get_by_natural_key()``. If you don't want Django to output
    
  527.     natural keys during serialization, but you want to retain the
    
  528.     ability to load natural keys, then you can opt to not implement
    
  529.     the ``natural_key()`` method.
    
  530. 
    
  531.     Conversely, if (for some strange reason) you want Django to output
    
  532.     natural keys during serialization, but *not* be able to load those
    
  533.     key values, just don't define the ``get_by_natural_key()`` method.
    
  534. 
    
  535. .. _natural-keys-and-forward-references:
    
  536. 
    
  537. Natural keys and forward references
    
  538. -----------------------------------
    
  539. 
    
  540. Sometimes when you use :ref:`natural foreign keys
    
  541. <topics-serialization-natural-keys>` you'll need to deserialize data where
    
  542. an object has a foreign key referencing another object that hasn't yet been
    
  543. deserialized. This is called a "forward reference".
    
  544. 
    
  545. For instance, suppose you have the following objects in your fixture::
    
  546. 
    
  547.     ...
    
  548.     {
    
  549.         "model": "store.book",
    
  550.         "fields": {
    
  551.             "name": "Mostly Harmless",
    
  552.             "author": ["Douglas", "Adams"]
    
  553.         }
    
  554.     },
    
  555.     ...
    
  556.     {
    
  557.         "model": "store.person",
    
  558.         "fields": {
    
  559.             "first_name": "Douglas",
    
  560.             "last_name": "Adams"
    
  561.         }
    
  562.     },
    
  563.     ...
    
  564. 
    
  565. In order to handle this situation, you need to pass
    
  566. ``handle_forward_references=True`` to ``serializers.deserialize()``. This will
    
  567. set the ``deferred_fields`` attribute on the ``DeserializedObject`` instances.
    
  568. You'll need to keep track of ``DeserializedObject`` instances where this
    
  569. attribute isn't ``None`` and later call ``save_deferred_fields()`` on them.
    
  570. 
    
  571. Typical usage looks like this::
    
  572. 
    
  573.     objs_with_deferred_fields = []
    
  574. 
    
  575.     for obj in serializers.deserialize('xml', data, handle_forward_references=True):
    
  576.         obj.save()
    
  577.         if obj.deferred_fields is not None:
    
  578.             objs_with_deferred_fields.append(obj)
    
  579. 
    
  580.     for obj in objs_with_deferred_fields:
    
  581.         obj.save_deferred_fields()
    
  582. 
    
  583. For this to work, the ``ForeignKey`` on the referencing model must have
    
  584. ``null=True``.
    
  585. 
    
  586. Dependencies during serialization
    
  587. ---------------------------------
    
  588. 
    
  589. It's often possible to avoid explicitly having to handle forward references by
    
  590. taking care with the ordering of objects within a fixture.
    
  591. 
    
  592. To help with this, calls to :djadmin:`dumpdata` that use the :option:`dumpdata
    
  593. --natural-foreign` option will serialize any model with a ``natural_key()``
    
  594. method before serializing standard primary key objects.
    
  595. 
    
  596. However, this may not always be enough. If your natural key refers to
    
  597. another object (by using a foreign key or natural key to another object
    
  598. as part of a natural key), then you need to be able to ensure that
    
  599. the objects on which a natural key depends occur in the serialized data
    
  600. before the natural key requires them.
    
  601. 
    
  602. To control this ordering, you can define dependencies on your
    
  603. ``natural_key()`` methods. You do this by setting a ``dependencies``
    
  604. attribute on the ``natural_key()`` method itself.
    
  605. 
    
  606. For example, let's add a natural key to the ``Book`` model from the
    
  607. example above::
    
  608. 
    
  609.     class Book(models.Model):
    
  610.         name = models.CharField(max_length=100)
    
  611.         author = models.ForeignKey(Person, on_delete=models.CASCADE)
    
  612. 
    
  613.         def natural_key(self):
    
  614.             return (self.name,) + self.author.natural_key()
    
  615. 
    
  616. The natural key for a ``Book`` is a combination of its name and its
    
  617. author. This means that ``Person`` must be serialized before ``Book``.
    
  618. To define this dependency, we add one extra line::
    
  619. 
    
  620.         def natural_key(self):
    
  621.             return (self.name,) + self.author.natural_key()
    
  622.         natural_key.dependencies = ['example_app.person']
    
  623. 
    
  624. This definition ensures that all ``Person`` objects are serialized before
    
  625. any ``Book`` objects. In turn, any object referencing ``Book`` will be
    
  626. serialized after both ``Person`` and ``Book`` have been serialized.