PageRenderTime 52ms CodeModel.GetById 30ms app.highlight 2ms RepoModel.GetById 18ms app.codeStats 0ms

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