dur*_*enk 39
您需要创建一个空的迁移文件,并在操作块中执行您的操作,如文档中所述.
除了更改数据库模式之外,您还可以根据需要使用迁移来更改数据库本身中的数据以及模式.
现在,您需要做的就是创建一个新函数并让RunPython使用它
Docs通过一个示例解释了这一点,展示了如何与模型进行通信.
来自Docs
要创建空的迁移文件,
python manage.py makemigrations --empty yourappname
Run Code Online (Sandbox Code Playgroud)
这是如何更新新添加的字段的示例.
# -*- 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),
]
Run Code Online (Sandbox Code Playgroud)
Sar*_*iev 13
我想你要找的是fixtures https://docs.djangoproject.com/en/1.10/howto/initial-data/
来自docs
在您首次设置应用程序时,使用硬编码数据预填充数据库有时很有用.您可以通过灯具提供初始数据.
另请阅读https://code.djangoproject.com/wiki/Fixtures
接受的答案很好。但是,由于OP在添加新行而不更新现有条目的上下文中提出了问题。这是用于添加新条目的代码段:
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),
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13024 次 |
| 最近记录: |