This is a very simple example. Please read something more complex if you need.

Fixtures are very powerful to play with your database sample data during development process. After each python reset <myapp> command you need to populate database with sample data again and again using admin interface. It's quite boring, isn't it? With fixtures our life became more comfortable and easy. Look at this example. Lets imagine that you have some data in db. We can dump it, even if your models have ForeignKeys or any kind of *To* relations.

First we need to define fixtures dir in settings file:


Lets dump our data:

cd /path/to/my_project
python dumpdata --format=json myapp > /path/to/myapp/fixtures/initial_data.json


python reset myapp

You have requested a database reset.
This will IRREVERSIBLY DESTROY any data for
the "myapp" application in the database "mydb".
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes

Now we have clean DB, lets populate it with our sample data:

python syncdb
Loading 'initial_data' fixtures...
Installing json fixture 'initial_data' from '/path/to/myapp/fixtures/'.
Installed 24 object(s) from 1 fixture(s)

Fixture loading

The location where Django loads a fixture from might seem unintuitive. As with template files, the fixtures of all applications in a project share the same namespace. If you follow [source:django/trunk/django/core/management/commands/] you see that Django searches for *appnames*/fixtures and settings.FIXTURE_DIRS and loads the first match. So if you use names like testdata.json for your fixtures you must make sure that no other active application uses a fixture with the same name. If not, you can never be sure what fixtures you actually load.

Therefore it is suggested that you qualify your fixtures with the name of the associated application. One strategy for this is to use the application name as a filename prefix, as in myapp/fixtures/myapp_testdata.json. Another strategy, which is consistent with that recommended for templates and static files in the Django documentation, is to put your application fixtures in a application-named subdirectory, as in myapp/fixtures/myapp/testdata.json. Both of these conventions work well with loaddata.


Last modified 7 months ago Last modified on 07/31/2016 11:00:01 AM
Back to Top