我有一堆新的权限,我需要迁移.我尝试通过数据迁移来做,但抱怨ContentType not being available.
快速研究我发现ContentType在应用所有迁移后填充表.
我甚至尝试使用update_all_contenttypes()从中from django.contrib.contenttypes.management import update_all_contenttypes
导致迁移加载与夹具不一致的数据.
在Django中迁移权限数据的最佳方法是什么?
有两种方法可以解决这个问题:
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....
Run Code Online (Sandbox Code Playgroud)
以下是向User模型添加自定义权限的步骤:
首先创建一个迁移文件,例如在您的身份验证应用程序下,
我在这里命名它0002_permission_fixtures.py:
account (your authentication application)
|_migrations
|__ 0001_initial.py
|__ 0002_permission_fixtures.py
|__ __init__.py
Run Code Online (Sandbox Code Playgroud)
然后添加您的权限对象,如下所示:
# -*- 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,
),
]
Run Code Online (Sandbox Code Playgroud)
要运行此迁移,首先迁移contenttype模型,然后迁移您的应用程序(这里是帐户)。
$ python manage.py migrate contenttypes
$ python manage.py migrate account
Run Code Online (Sandbox Code Playgroud)
这是确保已创建所有应用程序的所有权限的快速而肮脏的方法:
def add_all_permissions():
from django.apps import apps
from django.contrib.auth.management import create_permissions
for app_config in apps.get_app_configs():
app_config.models_module = True
create_permissions(app_config, verbosity=0)
app_config.models_module = None
Run Code Online (Sandbox Code Playgroud)