2017年10月8日 星期日

[Django] Models - intialize data

 Python   Django   Models  



Introduction


We will learn how to initialize data into database for Models.

Environment


Python 3.6.2
Django 1.8.18



Implement



Create Model objects

{migration_name}.py

from django.db import migrations, models

# Initialize ProductTypes
def initProdustTypes(apps, schema_editor):
    ptModel = apps.get_model("app", "ProductType") #apps.get_model(app_label, model_name, require_ready=True)
    ptDataBook = ptModel(Id=1, Name='Book')
    ptDataBook.save()
    ptDataClothes = ptModel(Id=2, Name='Clothes')
    ptDataClothes.save()
    ptDataToy = ptModel(Id=3, Name='Toy')
    ptDataToy.save()
   

# Remove all records in ProductTypes
def removeProductTypes(apps, schema_editor):
    ptModel = apps.get_model("app", "ProductType")
    ptModel.objects.all().delete()

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.RunPython(initProdustTypes,removeProductTypes)
    ]




SQL statement
We can also use SQL for initializing the data.

Install sqlparse for parse

We will need sqlparse to parse the sql statement.

$ python –m pip install sqlparse


{migration_name}.py


from django.db import migrations, models

def initProdustTypesSql():
   
    sql = """
      INSERT INTO ProductTypes VALUES(1, 'Book');
      INSERT INTO ProductTypes VALUES(2, 'Clothes');
      INSERT INTO ProductTypes VALUES(3, 'Toy');
    """
    return sql

def removeProductTypesSql():
    return 'DELETE from ProductTypes'   

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.RunSQL(initProdustTypesSql(), removeProductTypesSql())
    ]




Github





Reference






沒有留言:

張貼留言