创建一个创建组的django数据迁移的正确方法? [英] right way to create a django data migration that creates a group?
问题描述
我想创建创建权限和组的数据迁移,以便我的其他开发人员可以运行迁移并获取所有设置。我能够创建迁移并运行它们很好,但是现在我在运行测试时遇到错误。
但是如果我这样做:
从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屋!