我之前有一个没有迁移的新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)
]
Run Code Online (Sandbox Code Playgroud)
我有一个名为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()
Run Code Online (Sandbox Code Playgroud)
我遵循的模式是从初始迁移开始:
> python manage.py makemigrations
Run Code Online (Sandbox Code Playgroud)
这将创建用于构建表的迁移.
接下来,我为数据创建一个空迁移:
> python manage.py makemigrations --empty core
Run Code Online (Sandbox Code Playgroud)
然后,我使用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),
]
Run Code Online (Sandbox Code Playgroud)
首先,这不可能是第一次迁移,因为您需要迁移来实际创建类型表。你至少需要依赖它。
其次,一旦有了 Type 模型,就可以像处理普通 Django 代码一样对待它;实例化它,设置它的属性,保存它,等等。
| 归档时间: |
|
| 查看次数: |
3551 次 |
| 最近记录: |