2
0

fixtures.txt 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. .. _fixtures-explanation:
  2. ========
  3. Fixtures
  4. ========
  5. A *fixture* is a collection of files that contain the serialized contents of
  6. the database. Each fixture has a unique name, and the files that comprise the
  7. fixture can be distributed over multiple directories, in multiple applications.
  8. .. seealso::
  9. * :doc:`/howto/initial-data`
  10. How to produce a fixture
  11. ========================
  12. Fixtures can be generated by :djadmin:`manage.py dumpdata <dumpdata>`. It's
  13. also possible to generate custom fixtures by directly using :doc:`serialization
  14. tools </topics/serialization>` or even by handwriting them.
  15. How to use a fixture
  16. ====================
  17. Fixtures can be used to pre-populate the database with data for
  18. :ref:`tests <topics-testing-fixtures>`:
  19. .. code-block:: python
  20. class MyTestCase(TestCase):
  21. fixtures = ["fixture-label"]
  22. or to provide some :ref:`initial data <initial-data-via-fixtures>` using the
  23. :djadmin:`loaddata` command:
  24. .. code-block:: shell
  25. django-admin loaddata <fixture label>
  26. How fixtures are discovered
  27. ===========================
  28. Django will search in these locations for fixtures:
  29. 1. In the ``fixtures`` directory of every installed application
  30. 2. In any directory listed in the :setting:`FIXTURE_DIRS` setting
  31. 3. In the literal path named by the fixture
  32. Django will load any and all fixtures it finds in these locations that match
  33. the provided fixture names. If the named fixture has a file extension, only
  34. fixtures of that type will be loaded. For example:
  35. .. code-block:: shell
  36. django-admin loaddata mydata.json
  37. would only load JSON fixtures called ``mydata``. The fixture extension must
  38. correspond to the registered name of a
  39. :ref:`serializer <serialization-formats>` (e.g., ``json`` or ``xml``).
  40. If you omit the extensions, Django will search all available fixture types for
  41. a matching fixture. For example:
  42. .. code-block:: shell
  43. django-admin loaddata mydata
  44. would look for any fixture of any fixture type called ``mydata``. If a fixture
  45. directory contained ``mydata.json``, that fixture would be loaded as a JSON
  46. fixture.
  47. The fixtures that are named can include directory components. These directories
  48. will be included in the search path. For example:
  49. .. code-block:: shell
  50. django-admin loaddata foo/bar/mydata.json
  51. would search ``<app_label>/fixtures/foo/bar/mydata.json`` for each installed
  52. application, ``<dirname>/foo/bar/mydata.json`` for each directory in
  53. :setting:`FIXTURE_DIRS`, and the literal path ``foo/bar/mydata.json``.
  54. Fixtures loading order
  55. ----------------------
  56. Multiple fixtures can be specified in the same invocation. For example:
  57. .. code-block:: shell
  58. django-admin loaddata mammals birds insects
  59. or in a test case class:
  60. .. code-block:: python
  61. class AnimalTestCase(TestCase):
  62. fixtures = ["mammals", "birds", "insects"]
  63. The order in which fixtures are loaded follows the order in which they are
  64. listed, whether it's when using the management command or when listing them in
  65. the test case class as shown above.
  66. In these examples, all the fixtures named ``mammals`` from all applications (in
  67. the order in which applications are defined in :setting:`INSTALLED_APPS`) will
  68. be loaded first. Subsequently, all the ``birds`` fixtures will be loaded,
  69. followed by all the ``insects`` fixtures.
  70. Be aware that if the database backend supports row-level constraints, these
  71. constraints will be checked at the end of the transaction. Any relationships
  72. across fixtures may result in a load error if the database configuration does
  73. not support deferred constraint checking (refer to the `MySQL`_ docs for an
  74. example).
  75. .. _MySQL: https://dev.mysql.com/doc/refman/en/constraint-foreign-key.html
  76. How fixtures are saved to the database
  77. ======================================
  78. When fixture files are processed, the data is saved to the database as is.
  79. Model defined :meth:`~django.db.models.Model.save` methods are not called, and
  80. any :data:`~django.db.models.signals.pre_save` or
  81. :data:`~django.db.models.signals.post_save` signals will be called with
  82. ``raw=True`` since the instance only contains attributes that are local to the
  83. model. You may, for example, want to disable handlers that access
  84. related fields that aren't present during fixture loading and would otherwise
  85. raise an exception::
  86. from django.db.models.signals import post_save
  87. from .models import MyModel
  88. def my_handler(**kwargs):
  89. # disable the handler during fixture loading
  90. if kwargs["raw"]:
  91. return
  92. ...
  93. post_save.connect(my_handler, sender=MyModel)
  94. You could also write a decorator to encapsulate this logic::
  95. from functools import wraps
  96. def disable_for_loaddata(signal_handler):
  97. """
  98. Decorator that turns off signal handlers when loading fixture data.
  99. """
  100. @wraps(signal_handler)
  101. def wrapper(*args, **kwargs):
  102. if kwargs["raw"]:
  103. return
  104. signal_handler(*args, **kwargs)
  105. return wrapper
  106. @disable_for_loaddata
  107. def my_handler(**kwargs): ...
  108. Just be aware that this logic will disable the signals whenever fixtures are
  109. deserialized, not just during :djadmin:`loaddata`.
  110. Compressed fixtures
  111. ===================
  112. Fixtures may be compressed in ``zip``, ``gz``, ``bz2``, ``lzma``, or ``xz``
  113. format. For example:
  114. .. code-block:: shell
  115. django-admin loaddata mydata.json
  116. would look for any of ``mydata.json``, ``mydata.json.zip``, ``mydata.json.gz``,
  117. ``mydata.json.bz2``, ``mydata.json.lzma``, or ``mydata.json.xz``. The first
  118. file contained within a compressed archive is used.
  119. Note that if two fixtures with the same name but different fixture type are
  120. discovered (for example, if ``mydata.json`` and ``mydata.xml.gz`` were found in
  121. the same fixture directory), fixture installation will be aborted, and any data
  122. installed in the call to :djadmin:`loaddata` will be removed from the database.
  123. .. admonition:: MySQL with MyISAM and fixtures
  124. The MyISAM storage engine of MySQL doesn't support transactions or
  125. constraints, so if you use MyISAM, you won't get validation of fixture
  126. data, or a rollback if multiple transaction files are found.
  127. Database-specific fixtures
  128. ==========================
  129. If you're in a multi-database setup, you might have fixture data that
  130. you want to load onto one database, but not onto another. In this
  131. situation, you can add a database identifier into the names of your fixtures.
  132. For example, if your :setting:`DATABASES` setting has a ``users`` database
  133. defined, name the fixture ``mydata.users.json`` or
  134. ``mydata.users.json.gz`` and the fixture will only be loaded when you
  135. specify you want to load data into the ``users`` database.