我有一堆需要迁移的新权限。我试过通过数据迁移来做这件事,但抱怨ContentType not being available。
通过快速研究,我发现ContentType表是在应用所有迁移之后填充的。
我甚至尝试使用from django.contrib.contenttypes.management import update_all_contenttypes中的update_all_contenttypes(),这会导致迁移加载与fixture不一致的数据。
在Django中迁移权限数据的最佳方式是什么?
发布于 2015-12-15 01:03:10
有两种方法可以解决这个问题:
1)丑陋的方式:
在想要的迁移之前运行manage.py migrate auth
2)推荐方式:
from django.contrib.auth.management import create_permissions
def add_permissions(apps, schema_editor):
apps.models_module = True
create_permissions(apps, verbosity=0)
apps.models_module = None
# rest of code here....发布于 2017-05-05 02:32:16
这里有一个快速而肮脏的方法,可以确保所有应用程序的所有权限都已创建:
def add_all_permissions(apps=None, schema_editor=None):
from django.contrib.auth.management import create_permissions
if apps is None:
from django.apps import apps
for app_config in apps.get_app_configs():
app_config.models_module = True
create_permissions(app_config, verbosity=0)
app_config.models_module = None
class Migration(migrations.Migration):
dependencies = [('myapp', '0123_do_the_thing')]
operations = [
migrations.RunPython(add_all_permissions,
reverse_code=migrations.RunPython.noop)
# ...
]注:编辑后包含了ruohola的优秀建议
发布于 2015-09-22 07:20:13
以下是向User模型添加自定义权限的步骤:
首先创建一个迁移文件,例如在您的身份验证应用程序下,
这里我将其命名为0002_permission_fixtures.py
account (your authentication application)
|_migrations
|__ 0001_initial.py
|__ 0002_permission_fixtures.py
|__ __init__.py然后添加您的权限对象,如下所示:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
# Get models that we needs them
user = apps.get_model("auth", "User")
permission = apps.get_model("auth", "Permission")
content_type = apps.get_model("contenttypes", "ContentType")
# Get user content type object
uct = content_type.objects.get_for_model(user)
db_alias = schema_editor.connection.alias
# Adding your custom permissions to User model:
permission.objects.using(db_alias).bulk_create([
permission(codename='add_sample', name='Can add sample', content_type=uct),
permission(codename='change_sample', name='Can change sample', content_type=uct),
permission(codename='delete_sample', name='Can delete sample', content_type=uct),
])
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '__latest__'),
]
operations = [
migrations.RunPython(
forwards_func,
),
]要运行此迁移,首先迁移contenttype模型,然后迁移您的应用程序(此处为account)。
$ python manage.py migrate contenttypes
$ python manage.py migrate accounthttps://stackoverflow.com/questions/29296757
复制相似问题