创建一个创建组的django数据迁移的正确方法? [英] right way to create a django data migration that creates a group?

查看:127
本文介绍了创建一个创建组的django数据迁移的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建创建权限和组的数据迁移,以便我的其他开发人员可以运行迁移并获取所有设置。我能够创建迁移并运行它们很好,但是现在我在运行测试时遇到错误。



但是如果我这样做:


 从django.contrib.auth.models导入组

def add_operations_group(apps,schema_editor):
Group.objects.get_or_create(name ='operations')

我得到:

  django.db.utils.OperationalError:没有这样的表:auth_group 

如果我这样做:

  def add_operations_group(apps,schema_editor):
Group = apps.get_model(django.contrib.auth,group)
Group.objects.get_or_create(name ='operations')

我得到:

  LookupError: django.contrib.auth'

有没有办法做到这一点?还是有一个Django方式来确保创建权限和组的东西?

解决方案

这是我做的:






$应用_migration(应用程序, schema_editor)
Group = apps.get_model('auth','Group')
Group.objects.bulk_create([
Group(name = u'group1'))
Group(name = u'group2'),
Group(name = u'group3'),
])


def revert_migration(apps,schema_editor)
Group = apps.get_model('auth','Group')
Group.objects.filter(
name__in = [
u'group1',
u' group2',
u'group3',
]
).delete()


class Migration(migrations.Migration):

dependencies = [
('someapp','XXXX_some_migration'),
]

operations = [
migrations.RunPython(apply_migration,revert_migration)
]

虽然,必须是更加Djangonic的方式。


I would like to create data migrations that create Permissions and Groups, so that my other developers can just run the migrations and get everything set up. I was able to create the migrations and run them just fine, but now I'm getting an error when running my tests.

But if I do this:

from django.contrib.auth.models import Group

def add_operations_group(apps, schema_editor):
    Group.objects.get_or_create(name='operations')

I get:

django.db.utils.OperationalError: no such table: auth_group

If I do this:

def add_operations_group(apps, schema_editor):
    Group = apps.get_model("django.contrib.auth", "group")
    Group.objects.get_or_create(name='operations')

I get:

LookupError: No installed app with label 'django.contrib.auth'

Is there a way to do this? Or is there a "Django Way" to make sure things like permissions and groups are created?

解决方案

This is how I do it:

from django.db import models, migrations


def apply_migration(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    Group.objects.bulk_create([
        Group(name=u'group1'),
        Group(name=u'group2'),
        Group(name=u'group3'),
    ])


def revert_migration(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    Group.objects.filter(
        name__in=[
            u'group1',
            u'group2',
            u'group3',
        ]
    ).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('someapp', 'XXXX_some_migration'),
    ]

    operations = [
        migrations.RunPython(apply_migration, revert_migration)
    ]

Although, there must be a more Djangonic way.

这篇关于创建一个创建组的django数据迁移的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆