Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create new objects in django data migration?

Tags:

python

django

I have a new django project with no migrations before, therefore I want to create my first migration which inserts some rows into a table. This is what I have yet:

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

from django.db import migrations, models


def create_types(apps, schema_editor):
    Type = apps.get_model("core", "Type")
    type = Type()


class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.RunPython(create_types)
    ]

I have an application core which has model named Type, and I want to create few types and set attributes for them, and all of them save into database. How to create a new object of Type model here? Also other question, if this is very first migrator can I leave the dependencies empty? The file I created with this tutorial https://docs.djangoproject.com/en/1.8/topics/migrations/#data-migrations named it 0001_initial.py

EDIT: solved, creating model like this works, my overseight.

Type = apps.get_model("core", "Type")
    type = Type()
type.prop = '..'
type.save()
like image 971
Pink Avatar asked Mar 02 '16 18:03

Pink


1 Answers

The pattern I follow is to start with an initial migration:

> python manage.py makemigrations

This creates the migrations to build your table.

Next, I create an empty migration for the data:

> python manage.py makemigrations --empty core

Then I edit the newly created migration file with the data migration using the RunPython function. The pattern in the docs is a little different compared to the other answer here:

https://docs.djangoproject.com/en/1.11/ref/migration-operations/

def create_types(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    Type = apps.get_model("core", "Type")
    Type.objects.using(db_alias).create(property=value)

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(create_types),
    ]
like image 117
mattdedek Avatar answered Dec 21 '22 18:12

mattdedek