initial-data.txt 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. =================================
  2. Providing initial data for models
  3. =================================
  4. It's sometimes useful to pre-populate your database with hard-coded data when
  5. you're first setting up an app. There's a couple of ways you can have Django
  6. automatically create this data: you can provide `initial data via fixtures`_, or
  7. you can provide `initial data as SQL`_.
  8. In general, using a fixture is a cleaner method since it's database-agnostic,
  9. but initial SQL is also quite a bit more flexible.
  10. .. _initial data as sql: `providing initial sql data`_
  11. .. _initial data via fixtures: `providing initial data with fixtures`_
  12. .. _initial-data-via-fixtures:
  13. Providing initial data with fixtures
  14. ====================================
  15. A fixture is a collection of data that Django knows how to import into a
  16. database. The most straightforward way of creating a fixture if you've already
  17. got some data is to use the :djadmin:`manage.py dumpdata <dumpdata>` command.
  18. Or, you can write fixtures by hand; fixtures can be written as XML, YAML, or
  19. JSON documents. The :doc:`serialization documentation </topics/serialization>`
  20. has more details about each of these supported :ref:`serialization formats
  21. <serialization-formats>`.
  22. As an example, though, here's what a fixture for a simple ``Person`` model might
  23. look like in JSON:
  24. .. code-block:: js
  25. [
  26. {
  27. "model": "myapp.person",
  28. "pk": 1,
  29. "fields": {
  30. "first_name": "John",
  31. "last_name": "Lennon"
  32. }
  33. },
  34. {
  35. "model": "myapp.person",
  36. "pk": 2,
  37. "fields": {
  38. "first_name": "Paul",
  39. "last_name": "McCartney"
  40. }
  41. }
  42. ]
  43. And here's that same fixture as YAML:
  44. .. code-block:: none
  45. - model: myapp.person
  46. pk: 1
  47. fields:
  48. first_name: John
  49. last_name: Lennon
  50. - model: myapp.person
  51. pk: 2
  52. fields:
  53. first_name: Paul
  54. last_name: McCartney
  55. You'll store this data in a ``fixtures`` directory inside your app.
  56. Loading data is easy: just call :djadmin:`manage.py loaddata <loaddata>`
  57. ``<fixturename>``, where ``<fixturename>`` is the name of the fixture file
  58. you've created. Each time you run :djadmin:`loaddata`, the data will be read
  59. from the fixture and re-loaded into the database. Note this means that if you
  60. change one of the rows created by a fixture and then run :djadmin:`loaddata`
  61. again, you'll wipe out any changes you've made.
  62. Automatically loading initial data fixtures
  63. -------------------------------------------
  64. .. deprecated:: 1.7
  65. If an application uses migrations, there is no automatic loading of
  66. fixtures. Since migrations will be required for applications in Django 1.9,
  67. this behavior is considered deprecated. If you want to load initial data
  68. for an app, consider doing it in a migration.
  69. If you create a fixture named ``initial_data.[xml/yaml/json]``, that fixture will
  70. be loaded every time you run :djadmin:`migrate`. This is extremely convenient,
  71. but be careful: remember that the data will be refreshed *every time* you run
  72. :djadmin:`migrate`. So don't use ``initial_data`` for data you'll want to edit.
  73. Where Django finds fixture files
  74. --------------------------------
  75. By default, Django looks in the ``fixtures`` directory inside each app for
  76. fixtures. You can set the :setting:`FIXTURE_DIRS` setting to a list of
  77. additional directories where Django should look.
  78. When running :djadmin:`manage.py loaddata <loaddata>`, you can also
  79. specify a path to a fixture file, which overrides searching the usual
  80. directories.
  81. .. seealso::
  82. Fixtures are also used by the :ref:`testing framework
  83. <topics-testing-fixtures>` to help set up a consistent test environment.
  84. .. _initial-sql:
  85. Providing initial SQL data
  86. ==========================
  87. .. deprecated:: 1.7
  88. If an application uses migrations, there is no loading of initial SQL data
  89. (including backend-specific SQL data). Since migrations will be required
  90. for applications in Django 1.9, this behavior is considered deprecated.
  91. If you want to use initial SQL for an app, consider doing it in a migration.
  92. Django provides a hook for passing the database arbitrary SQL that's executed
  93. just after the CREATE TABLE statements when you run :djadmin:`migrate`. You can
  94. use this hook to populate default records, or you could also create SQL
  95. functions, views, triggers, etc.
  96. The hook is simple: Django just looks for a file called ``sql/<modelname>.sql``,
  97. in your app directory, where ``<modelname>`` is the model's name in lowercase.
  98. So, if you had a ``Person`` model in an app called ``myapp``, you could add
  99. arbitrary SQL to the file ``sql/person.sql`` inside your ``myapp`` directory.
  100. Here's an example of what the file might contain:
  101. .. code-block:: sql
  102. INSERT INTO myapp_person (first_name, last_name) VALUES ('John', 'Lennon');
  103. INSERT INTO myapp_person (first_name, last_name) VALUES ('Paul', 'McCartney');
  104. Each SQL file, if given, is expected to contain valid SQL statements
  105. which will insert the desired data (e.g., properly-formatted
  106. ``INSERT`` statements separated by semicolons).
  107. The SQL files are read by the :djadmin:`sqlcustom` and :djadmin:`sqlall`
  108. commands in :doc:`manage.py </ref/django-admin>`. Refer to the :doc:`manage.py
  109. documentation </ref/django-admin>` for more information.
  110. Note that if you have multiple SQL data files, there's no guarantee of
  111. the order in which they're executed. The only thing you can assume is
  112. that, by the time your custom data files are executed, all the
  113. database tables already will have been created.
  114. .. admonition:: Initial SQL data and testing
  115. This technique *cannot* be used to provide initial data for
  116. testing purposes. Django's test framework flushes the contents of
  117. the test database after each test; as a result, any data added
  118. using the custom SQL hook will be lost.
  119. If you require data for a test case, you should add it using
  120. either a :ref:`test fixture <topics-testing-fixtures>`, or
  121. programmatically add it during the ``setUp()`` of your test case.
  122. Database-backend-specific SQL data
  123. ----------------------------------
  124. There's also a hook for backend-specific SQL data. For example, you
  125. can have separate initial-data files for PostgreSQL and SQLite. For
  126. each app, Django looks for a file called
  127. ``<app_label>/sql/<modelname>.<backend>.sql``, where ``<app_label>`` is
  128. your app directory, ``<modelname>`` is the model's name in lowercase
  129. and ``<backend>`` is the last part of the module name provided for the
  130. :setting:`ENGINE <DATABASE-ENGINE>` in your settings file (e.g., if you have
  131. defined a database with an :setting:`ENGINE <DATABASE-ENGINE>` value of
  132. ``django.db.backends.sqlite3``, Django will look for
  133. ``<app_label>/sql/<modelname>.sqlite3.sql``).
  134. Backend-specific SQL data is executed before non-backend-specific SQL
  135. data. For example, if your app contains the files ``sql/person.sql``
  136. and ``sql/person.sqlite3.sql`` and you're installing the app on
  137. SQLite, Django will execute the contents of
  138. ``sql/person.sqlite3.sql`` first, then ``sql/person.sql``.