How to define default data for Django Models?

Dhanushka Amarakoon picture Dhanushka Amarakoon · Sep 28, 2016 · Viewed 20.2k times · Source

I want my application to have default data such as user types.

What's the most efficient way to manage default data after migrations?

It needs to handle situations such as, after I add a new table, it adds the default data for it.

Answer

durdenk picture durdenk · Sep 28, 2016

You need to create an empty migration file and Do your stuff in operations block, as explained in docs.

Data Migrations

As well as changing the database schema, you can also use migrations to change the data in the database itself, in conjunction with the schema if you want.

Now, all you need to do is create a new function and have RunPython use it

Docs explains this with an example to show ,how to communicate with your models.

From Docs

To create an empty migration file,

python manage.py makemigrations --empty yourappname

And this is the example how to update a newly added field.

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

def combine_names(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Person = apps.get_model("yourappname", "Person")
    for person in Person.objects.all():
        person.name = "%s %s" % (person.first_name, person.last_name)
        person.save()

class Migration(migrations.Migration):
    initial = True

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(combine_names),
    ]