PageRenderTime 45ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

Plain Text | 153 lines | 120 code | 33 blank | 0 comment | 0 complexity | 6261b38c46256207428eddc227beed94 MD5 | raw file
Possible License(s): BSD-3-Clause
  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. Providing initial data with fixtures
  13. ====================================
  14. A fixture is a collection of data that Django knows how to import into a
  15. database. The most straightforward way of creating a fixture if you've already
  16. got some data is to use the :djadmin:` dumpdata <dumpdata>` command.
  17. Or, you can write fixtures by hand; fixtures can be written as XML, YAML, or
  18. JSON documents. The :doc:`serialization documentation </topics/serialization>`
  19. has more details about each of these supported :ref:`serialization formats
  20. <serialization-formats>`.
  21. As an example, though, here's what a fixture for a simple ``Person`` model might
  22. look like in JSON:
  23. .. code-block:: js
  24. [
  25. {
  26. "model": "myapp.person",
  27. "pk": 1,
  28. "fields": {
  29. "first_name": "John",
  30. "last_name": "Lennon"
  31. }
  32. },
  33. {
  34. "model": "myapp.person",
  35. "pk": 2,
  36. "fields": {
  37. "first_name": "Paul",
  38. "last_name": "McCartney"
  39. }
  40. }
  41. ]
  42. And here's that same fixture as YAML:
  43. .. code-block:: none
  44. - model: myapp.person
  45. pk: 1
  46. fields:
  47. first_name: John
  48. last_name: Lennon
  49. - model: myapp.person
  50. pk: 2
  51. fields:
  52. first_name: Paul
  53. last_name: McCartney
  54. You'll store this data in a ``fixtures`` directory inside your app.
  55. Loading data is easy: just call :djadmin:` loaddata fixturename
  56. <loaddata>`, where *fixturename* is the name of the fixture file you've created.
  57. Every time you run :djadmin:`loaddata` the data will be read from the fixture
  58. and re-loaded into the database. Note that this means that if you change one of
  59. the rows created by a fixture and then run :djadmin:`loaddata` again you'll
  60. wipe out any changes you've made.
  61. Automatically loading initial data fixtures
  62. -------------------------------------------
  63. If you create a fixture named ``initial_data.[xml/yaml/json]``, that fixture will
  64. be loaded every time you run :djadmin:`syncdb`. This is extremely convenient,
  65. but be careful: remember that the data will be refreshed *every time* you run
  66. :djadmin:`syncdb`. So don't use ``initial_data`` for data you'll want to edit.
  67. .. seealso::
  68. Fixtures are also used by the :ref:`testing framework
  69. <topics-testing-fixtures>` to help set up a consistent test environment.
  70. .. _initial-sql:
  71. Providing initial SQL data
  72. ==========================
  73. Django provides a hook for passing the database arbitrary SQL that's executed
  74. just after the CREATE TABLE statements when you run :djadmin:`syncdb`. You can
  75. use this hook to populate default records, or you could also create SQL
  76. functions, views, triggers, etc.
  77. The hook is simple: Django just looks for a file called ``sql/<modelname>.sql``,
  78. in your app directory, where ``<modelname>`` is the model's name in lowercase.
  79. So, if you had a ``Person`` model in an app called ``myapp``, you could add
  80. arbitrary SQL to the file ``sql/person.sql`` inside your ``myapp`` directory.
  81. Here's an example of what the file might contain:
  82. .. code-block:: sql
  83. INSERT INTO myapp_person (first_name, last_name) VALUES ('John', 'Lennon');
  84. INSERT INTO myapp_person (first_name, last_name) VALUES ('Paul', 'McCartney');
  85. Each SQL file, if given, is expected to contain valid SQL statements
  86. which will insert the desired data (e.g., properly-formatted
  87. ``INSERT`` statements separated by semicolons).
  88. The SQL files are read by the :djadmin:`sqlcustom`, :djadmin:`sqlreset`,
  89. :djadmin:`sqlall` and :djadmin:`reset` commands in :doc:`
  90. </ref/django-admin>`. Refer to the :doc:` documentation
  91. </ref/django-admin>` for more information.
  92. Note that if you have multiple SQL data files, there's no guarantee of
  93. the order in which they're executed. The only thing you can assume is
  94. that, by the time your custom data files are executed, all the
  95. database tables already will have been created.
  96. .. admonition:: Initial SQL data and testing
  97. This technique *cannot* be used to provide initial data for
  98. testing purposes. Django's test framework flushes the contents of
  99. the test database after each test; as a result, any data added
  100. using the custom SQL hook will be lost.
  101. If you require data for a test case, you should add it using
  102. either a :ref:`test fixture <topics-testing-fixtures>`, or
  103. programatically add it during the ``setUp()`` of your test case.
  104. Database-backend-specific SQL data
  105. ----------------------------------
  106. There's also a hook for backend-specific SQL data. For example, you
  107. can have separate initial-data files for PostgreSQL and MySQL. For
  108. each app, Django looks for a file called
  109. ``<appname>/sql/<modelname>.<backend>.sql``, where ``<appname>`` is
  110. your app directory, ``<modelname>`` is the model's name in lowercase
  111. and ``<backend>`` is the last part of the module name provided for the
  112. :setting:`ENGINE` in your settings file (e.g., if you have defined a
  113. database with an :setting:`ENGINE` value of
  114. ``django.db.backends.postgresql``, Django will look for
  115. ``<appname>/sql/<modelname>.postgresql.sql``).
  116. Backend-specific SQL data is executed before non-backend-specific SQL
  117. data. For example, if your app contains the files ``sql/person.sql``
  118. and ``sql/person.postgresql.sql`` and you're installing the app on
  119. PostgreSQL, Django will execute the contents of
  120. ``sql/person.postgresql.sql`` first, then ``sql/person.sql``.