Seattle Software Developers


Pugetworks Blog Archive!

django: Persistent Database data

If you wish to have a core set of data that pre-populates your database after running python manage.py syncdb, then you need to know about the dumpdb command and fixtures.


Fixtures are where you can place data that django will be used to populate the database when syncdb is called. They are usually found in one or more directories called fixtures inside your django app. Beware! The order the fixtures are loaded into the database is random, so if there are dependencies between separate fixtures then you will have problems. Consolidate the dependent fixtures to solve this.


Dumpdb is used to output a json representation of the database. This data is streamed from the database and so it is also possible to have dependency issues if a table references entries in the same table.

There are 2 important flags to know:

  • --indent=2 - This makes the output easy to read and edit.
  • --natural - This removes foreign key ids from the output and replaces it with the unique field in the referenced model. This is most notable with exporting Permissions. This not required, but is something to remember.

The last argument is the django app name and optionally the model name. So if your last argument is auth you will get everything related to that app. If you change the argument to auth.user, then you will only get the information from the user model under the auth app (aka auth_user table).


Say you want to maintain the superuser info. Run the following:

[shell]./manage.py dumpdata --indent=2 auth.user > initial_data.json[/shell]

You'll see that along the users that you've already created during the usual syncdb execution, a lot of other stuff was dumped. Deleting everything except for the superuser will result in something like:

[shell] [ { "pk": 1, "model": "auth.user", "fields": { "username": "admin", "first_name": "Admin", "last_name": "Strator", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2012-01-13T14:18:47", "groups": [], "user_permissions": [], "password": "pbkdf2_sha256$10000$MIath2Pzfcc8$vykFKAQ1A0XoGKrSQwwksDxjzLFGnocknZaChiPdeC8=", "email": "admin@mydomain.com", "date_joined": "2011-11-10T15:55:55" } } ] [/shell]

Save this file to one of your fixtures folders and each time you execute the syncdb command it will be automatically loaded by django.

Either with an empty database or your existing database, running [shell]python ./manage.py syncdb[/shell] will import the data from the initial_data.json file.

If this is a empty database, add the flag --noinput, to prevent the script from asking questions.

[shell]python ./manage.py syncdb --noinput[/shell]

There shouldn't be a prompt for a superuser and you should see a message at the end of the output indicating that your fixture was loaded.

Originally from: http://arthurkoziel.com/2008/09/04/automatical-superuser-creation-django/