如何为 Django 模型定义默认数据?

How to define default data for Django Models?

我希望我的应用程序具有默认数据,例如用户类型。

迁移后管理默认数据的最有效方法是什么?

它需要处理一些情况,例如,在我添加一个新的 table 之后,它会为其添加默认数据。

更新:

大多数用户正在寻找 中@durdenk 建议的数据迁移。但是 OP 所问的是关于一种在迁移 之后添加数据 的方法,这就是为什么这是被接受的答案。

原回答:

我想你要找的是fixtureshttps://docs.djangoproject.com/en/1.10/howto/initial-data/

来自文档

It’s sometimes useful to pre-populate your database with hard-coded data when you’re first setting up an app. You can provide initial data via fixtures.

另请阅读此文https://code.djangoproject.com/wiki/Fixtures

您需要创建一个空的迁移文件并在操作块中执行操作,如文档中所述。

Data Migrations

As well as changing the database schema, you can also use migrations to change the data in the database itself, in conjunction with the schema if you want.

Now, all you need to do is create a new function and have RunPython use it

Docs 通过示例解释了这一点,展示了如何与您的模型进行通信。

来自文档

要创建一个空的迁移文件,

python manage.py makemigrations --empty yourappname

这是更新新添加字段的示例。

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

上面给出的答案只是为了说明如何向 table 插入新行。

from django.db import migrations, models
from yourapp.models import <yourmodel>

def combine_names(apps, schema_editor):
    obj = <yourmodel>(arrib=value)
    obj.save()

例如,假设您有模型 Person

person = Person(first_name='raj', last_name='shah')
person.save()

接受的答案很好。但是,由于 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),
    ]