initial-data.txt 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. If you create a fixture named ``initial_data.[xml/yaml/json]``, that fixture will
  65. be loaded every time you run :djadmin:`migrate`. This is extremely convenient,
  66. but be careful: remember that the data will be refreshed *every time* you run
  67. :djadmin:`migrate`. So don't use ``initial_data`` for data you'll want to edit.
  68. Where Django finds fixture files
  69. --------------------------------
  70. By default, Django looks in the ``fixtures`` directory inside each app for
  71. fixtures. You can set the :setting:`FIXTURE_DIRS` setting to a list of
  72. additional directories where Django should look.
  73. When running :djadmin:`manage.py loaddata <loaddata>`, you can also
  74. specify a path to a fixture file, which overrides searching the usual
  75. directories.
  76. .. seealso::
  77. Fixtures are also used by the :ref:`testing framework
  78. <topics-testing-fixtures>` to help set up a consistent test environment.
  79. .. _initial-sql:
  80. Providing initial SQL data
  81. ==========================
  82. .. deprecated:: 1.8
  83. Historically this functionality has used regular expression parsing of the
  84. initial SQL which is a bit buggy. This parsing is now deprecated in favor
  85. of installing `sqlparse <https://pypi.python.org/pypi/sqlparse>`_; doing so
  86. will be required for this functionality in Django 2.0. You can install it
  87. using ``pip install sqlparse``.
  88. Django provides a hook for passing the database arbitrary SQL that's executed
  89. just after the CREATE TABLE statements when you run :djadmin:`migrate`. You can
  90. use this hook to populate default records, or you could also create SQL
  91. functions, views, triggers, etc.
  92. The hook is simple: Django just looks for a file called ``sql/<modelname>.sql``,
  93. in your app directory, where ``<modelname>`` is the model's name in lowercase.
  94. So, if you had a ``Person`` model in an app called ``myapp``, you could add
  95. arbitrary SQL to the file ``sql/person.sql`` inside your ``myapp`` directory.
  96. Here's an example of what the file might contain:
  97. .. code-block:: sql
  98. INSERT INTO myapp_person (first_name, last_name) VALUES ('John', 'Lennon');
  99. INSERT INTO myapp_person (first_name, last_name) VALUES ('Paul', 'McCartney');
  100. Each SQL file, if given, is expected to contain valid SQL statements
  101. which will insert the desired data (e.g., properly-formatted
  102. ``INSERT`` statements separated by semicolons).
  103. The SQL files are read by the :djadmin:`sqlcustom` and :djadmin:`sqlall`
  104. commands in :doc:`manage.py </ref/django-admin>`. Refer to the :doc:`manage.py
  105. documentation </ref/django-admin>` for more information.
  106. Note that if you have multiple SQL data files, there's no guarantee of
  107. the order in which they're executed. The only thing you can assume is
  108. that, by the time your custom data files are executed, all the
  109. database tables already will have been created.
  110. .. admonition:: Initial SQL data and testing
  111. This technique *cannot* be used to provide initial data for
  112. testing purposes. Django's test framework flushes the contents of
  113. the test database after each test; as a result, any data added
  114. using the custom SQL hook will be lost.
  115. If you require data for a test case, you should add it using
  116. either a :ref:`test fixture <topics-testing-fixtures>`, or
  117. programmatically add it during the ``setUp()`` of your test case.
  118. Database-backend-specific SQL data
  119. ----------------------------------
  120. There's also a hook for backend-specific SQL data. For example, you
  121. can have separate initial-data files for PostgreSQL and SQLite. For
  122. each app, Django looks for a file called
  123. ``<app_label>/sql/<modelname>.<backend>.sql``, where ``<app_label>`` is
  124. your app directory, ``<modelname>`` is the model's name in lowercase
  125. and ``<backend>`` is the last part of the module name provided for the
  126. :setting:`ENGINE <DATABASE-ENGINE>` in your settings file (e.g., if you have
  127. defined a database with an :setting:`ENGINE <DATABASE-ENGINE>` value of
  128. ``django.db.backends.sqlite3``, Django will look for
  129. ``<app_label>/sql/<modelname>.sqlite3.sql``).
  130. Backend-specific SQL data is executed before non-backend-specific SQL
  131. data. For example, if your app contains the files ``sql/person.sql``
  132. and ``sql/person.sqlite3.sql`` and you're installing the app on
  133. SQLite, Django will execute the contents of
  134. ``sql/person.sqlite3.sql`` first, then ``sql/person.sql``.