簡體   English   中英

如何在django數據遷移中創建新對象?

[英]How do I create new objects in django data migration?

我之前有一個沒有遷移的新django項目,因此我想創建我的第一個遷移,它將一些行插入到表中。 這就是我的意思:

# -*- 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)
    ]

我有一個名為Type的模型的應用程序核心,我想創建幾個類型並為它們設置屬性,並且所有這些都保存到數據庫中。 如何在這里創建Type模型的新對象? 還有一個問題,如果這是第一個遷移器,我可以將依賴項留空嗎? 我使用本教程創建的文件https://docs.djangoproject.com/en/1.8/topics/migrations/#data-migrations將其命名為0001_initial.py

編輯:解決,創建像這樣的模型,我的監督。

Type = apps.get_model("core", "Type")
    type = Type()
type.prop = '..'
type.save()

我遵循的模式是從初始遷移開始:

> python manage.py makemigrations

這將創建用於構建表的遷移。

接下來,我為數據創建一個空遷移:

> python manage.py makemigrations --empty core

然后,我使用RunPython函數編輯帶有數據遷移的新創建的遷移文件。 與其他答案相比,文檔中的模式略有不同:

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

首先,這不是第一次遷移,因為您需要實際創建Type表。 你至少需要依靠它。

其次,一旦你有了Type模型,就像在普通的Django代碼中一樣對待它; 實例化它,設置它的屬性,保存它,無論如何。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM