Django loaddata

Summary: in this tutorial, you’ll learn how to use the Django loaddata command to provide initial data for models.

Introduction to the Django loaddata command

The Django loaddata command allows you to load data from a file into the database. Typically, you use the dumpdata command to export data from a database and use the loaddata command to import data from the file into the same or another database.

The following shows the syntax of the loaddata command:

python manage.py loaddata fixture_nameCode language: Python (python)

A fixture is a collection of data files that Django will use to import into a database.

By convention, Django will look for the fixtures in the fixtures directory under each app and import data from them.

For example, the following shows the fixtures directory and hr.json file in the hr application of the project:

├── admin.py
├── apps.py
├── fixtures
|  └── hr.json
...Code language: Python (python)

The following shows the excerpt of the hr.json file:

[
  {
    "model": "hr.contact",
    "pk": 1,
    "fields": {
      "phone": "40812345678",
      "address": "101 N 1st Street, San Jose, CA"
    }
  },
  {
    "model": "hr.contact",
    "pk": 2,
    "fields": {
      "phone": "4081111111",
      "address": "202 N 1st Street, San Jose, CA"
    }
  },
...Code language: Python (python)

To load the hr.json to the database, you use the following loaddata command:

python manage.py loaddata hr.jsonCode language: Python (python)

Fixture directory settings

By default, Django finds the data files in the fixtures directory inside each app. To specify additional directories that contain the fixture files, you can set them in the FIXTURE_DIRS list in the settings.py file:

FIXTURE_DIRS = ['path/to/fixtures/dir', 'path/to/fixtures/dir2']Code language: Python (python)

Loading sample HR data using the Django loaddata command

We’ll use the loaddata command to load data from fixtures for the HR application of the Django project.

First, download the project source code and extract it to a directory:

Download the Django ORM project

The hr/fixtures directory has the data.json file that contains sample HR data.

Second, run the loaddata command to load data from the data.json file:

python manage.py loaddata data.jsonCode language: CSS (css)

It should output something like this:

Installed 471 object(s) from 1 fixture(s)Code language: JavaScript (javascript)

Summary

  • Use the Django loaddata command to load data from fixtures into the database.
Did you find this tutorial helpful ?