【问题标题】:How to define default data for Django Models?如何为 Django 模型定义默认数据?
【发布时间】:2017-02-05 22:59:07
【问题描述】:

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

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

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

【问题讨论】:

    标签: django django-models django-orm django-migrations


    【解决方案1】:

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

    Data Migrations

    除了更改数据库架构外,您还可以使用迁移来更改数据库本身中的数据,如果需要,还可以与架构一起使用。

    现在,您需要做的就是创建一个新函数并让 RunPython 使用它

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

    【讨论】:

    • 工作得很好,但似乎需要将整个 Person 表加载到内存中......没有更好的方法来遍历所有 Person 对象吗?
    • Django 的方式是使用迭代器, Person.objects.all().iterator() ?尚未测试。
    • 这可以在与 0001 相同的迁移中完成,创建表之后?例如operations = [migrations.CreateModel(...), migrations.RunPython(...)]
    • 是的,操作是一个列表,您可以修改 django 创建的迁移文件并添加自己的功能。
    【解决方案2】:

    接受的答案很好。但是,由于 OP 在添加新行而不更新现有条目的上下文中提出了这个问题。这是用于添加新条目的代码 sn-p :

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

    【讨论】:

      【解决方案3】:

      更新:

      大多数用户正在寻找@durdenk 在https://stackoverflow.com/a/39742847/3627387 中建议的数据迁移。但是 OP 所问的是一种在迁移后添加数据的方法,这就是为什么这是被接受的答案。

      原答案

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

      来自文档

      在您首次设置应用程序时,使用硬编码数据预先填充数据库有时会很有用。您可以通过夹具提供初始数据。

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

      【讨论】:

      • 文档与此答案相矛盾:“如果您想自动加载应用程序的初始数据,请不要使用固定装置。相反,使用 RunPython 或 RunSQL 操作为您的应用程序创建迁移。”跨度>
      • @Dennis OP 询问“迁移后管理默认数据的最有效方法是什么”。即使有关于迁移的答案,他还是选择了我的答案作为他的问题的正确答案。
      • @Dennis 您在文档中使用的引用也是关于应用程序而不是关于项目的。
      • 在我看来,fixtures 的整个想法是主要为测试准备样本数据。这与为新表定义一些永久默认/系统/特殊记录无关,就像 OP 要求的那样。
      【解决方案4】:

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

      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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-15
        • 2011-08-01
        • 1970-01-01
        • 2011-06-04
        • 1970-01-01
        • 2020-05-11
        • 2016-03-23
        相关资源
        最近更新 更多