[Django]-How to define default data for Django Models?

15👍

Update:

most users are looking for data migration as suggested by @durdenk in https://stackoverflow.com/a/39742847/3627387. But what OP was asking is about a way to add data after migrations, that is why this is accepted answer.

Original answer:

I think what you are looking for is fixtures https://docs.djangoproject.com/en/1.10/howto/initial-data/

From docs

It’s sometimes useful to pre-populate your database with hard-coded data when you’re first setting up an app. You can provide initial data via fixtures.

Also read this https://code.djangoproject.com/wiki/Fixtures

62👍

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),
    ]

32👍

The accepted answer is fine. But, since OP asked the question in the context of adding new rows and not updating existing entries. Here is the code snippet for adding new entries :

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('loginmodule', '0002_login_avatar'),
    ]

    def insertData(apps, schema_editor):
     Login = apps.get_model('loginmodule', 'Login')
     user = Login(name = "admin", login_id = "admin", password = "password", email = "admin@pychat.com", type = "Admin", avatar="admin.jpg")
     user.save()


    operations = [
        migrations.RunPython(insertData),
    ]

-5👍

Answer is given above just to show how to insert new rows to the table.

from django.db import migrations, models
from yourapp.models import <yourmodel>

def combine_names(apps, schema_editor):
    obj = <yourmodel>(arrib=value)
    obj.save()

For example let’s say you have model Person

person = Person(first_name='raj', last_name='shah')
person.save()

Leave a comment