[Answer]-Django: How to make "python manage.py syncdb" not only create a DB but also fill it with data I need?

1đź‘Ť

âś…

From Django docs about fixtures:

Providing initial data with fixtures

A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you’ve already got some data is to use the manage.py dumpdata command. Or, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML (with PyYAML installed) documents. The serialization documentation has more details about each of these supported serialization formats.

Before version 1.7 Django there was a mechanism to load fixtures automatically:

If you create a fixture named initial_data.[xml/yaml/json], that fixture will be loaded every time you run migrate. This is extremely convenient, but be careful: remember that the data will be refreshed every time you run migrate. So don’t use initial_data for data you’ll want to edit.

If you are using Django>=1.7, you must issue the loaddata manage command or create a migration:

If an application uses migrations, there is no automatic loading of fixtures. Since migrations will be required for applications in Django 2.0, this behavior is considered deprecated. If you want to load initial data for an app, consider doing it in a data migration.

The JSON serializer used to choke on large inputs (tried to load everything in memory or something like that); the XML serializer used to behave better for larger fixtures.

0đź‘Ť

Assuming you are using Django 1.7, you can write a data migration to insert any data you need.

0đź‘Ť

There’s a whole django docs page about it.

In short, you have three options:

  • Provide a set of “fixtures”, that describe models. This way is DB agnostic and can be used with any DB django can talk to.
  • Provide a set of SQL scripts to run. Benefit you can get here is to use some database specific data types/programming capabilities/etc. However, it’s considered deprecated in Django 1.7 and will be removed in Django 2.0
  • Create a set of data migrations (comes with Django >=1.7, for earlier versions use South)

Also, loading initial data can occur every time migrate is run:

If you create a fixture named initial_data.[xml/yaml/json], that fixture will be loaded every time you run migrate. This is extremely convenient, but be careful: remember that the data will be refreshed every time you run migrate. So don’t use initial_data for data you’ll want to edit.

👤J0HN

Leave a comment