Loading initial data into Django

Sometimes. one of the requirements when building new models in your API, is to have them populated from the start with initial data. This can be the case with categorical data eg. product categories, job descriptions, credit rules, etc. Today I will show you how to achieve that, taking an animal healthcare app I’m building right now as an example - animal groups and names.

Example model

This is the model I have in my application. It uses the BaseModel class as foundation, you can read more about it here. As you can see, the model consists of two fields: name and group, and the fields taken from the BaseModel.

class AnimalType(BaseModel):
    HOME = 'home'
    FARM = 'farm'
    RODENTS = 'rodents'
    BIRDS = 'birds'
    EXOTIC = 'exotic'
    OTHER = 'other'
    GROUP_CHOICES = (
        (HOME, HOME),
        (FARM, FARM),
        (RODENTS, RODENTS),
        (BIRDS, BIRDS),
        (EXOTIC, EXOTIC),
        (OTHER, OTHER),
    )

    group = models.CharField(
        max_length=10,
        choices=GROUP_CHOICES,
    )
    name = models.CharField(
        max_length=30,
        unique=True,
    )

Creating fixtures

There are two ways of creating Django fixtures. You either populate the database and dump the data, or you create the file manually. Let’s start with the automatic way first. After you add the data to your database, you only need to run the following command:

manage.py dumpdata

If you prefer to do it by hand, you can create fixtures in three formats: json, xml or yaml. As json is the most popular format, let’s go with that. You file should look like this:

[
    {
        "model": "animals.animaltype",
        "fields": {
            "id": "1",
            "created_at": "2020-01-01T00:00:00+00:00",
            "updated_at": "2020-01-01T00:00:00+00:00",
            "group": "home",
            "name": "Dog"
        }
    },
    {
        "model": "animals.animaltype",
        "fields": {
            "id": "2",
            "created_at": "2020-01-01T00:00:00+00:00",
            "updated_at": "2020-01-01T00:00:00+00:00",
            "group": "home",
            "name": "Cat"
        }
    }
]

For automatic fixture discovery you need to throw it inside the fixtures directory (create one, if you don’t have it) of your Django application .

Loading fixtures

To load the fixtures you created inside your project you need to use manage.py like so:

manage.py loaddata your_fixture.json

You need to write that line for every fixture you plan to load. It is cool to write an init.sh file that could be run while running your docker containers, that runs everything you need, when you first publish your server:

#!/bin/sh

python manage.py migrate
python manage.py loaddata first_fixture.json
python manage.py loaddata second_fixture.json
# And so on, further fixtures

exec "$@"