我尝试为自定义用户类型编写数据迁移代码,但是当我尝试应用迁移时,我得到了这个:
TypeError: 'Permission' instance expected, got <Permission: my_app | Some Text | Can add some_model>
对我来说很奇怪。这不是一个Permission实例吗?这是我的自定义用户模型:
class Employee(AbstractUser):
middle_name = models.CharField(max_length=60, null=True, blank=True)
以下是迁移中的一段代码会引发此错误(我猜是这样):
for user in User.objects.all():
employee = orm.Employee.objects.create(
id=user.id,
username=user.username,
first_name=user.first_name,
last_name=user.last_name,
password=user.password,
email=user.email,
is_active=user.is_active,
is_superuser=user.is_superuser,
last_login=user.last_login,
date_joined=user.date_joined,
)
for perm in user.user_permissions.all():
employee.user_permissions.add(perm)
答案 0 :(得分:1)
我使用的是用户模型
from django.contrib.auth.models import AbstractUser
class MyProjectUser(AbstractUser):
...
我创建了迁移,以便为某些用户组添加新权限:
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
permissions_codenames = (
'can_action_1',
...
'can_action_10',
)
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
permissions = orm['auth.Permission'].objects.filter(codename__in=permissions_codenames)
for user in orm.MyProjectUser.objects.filter(groups__name__in=('GroupName1', 'GroupName2')):
user.user_permissions.add(*permissions)
def backwards(self, orm):
"Write your backwards methods here."
permissions = orm['auth.Permission'].objects.filter(codename__in=permissions_codenames)
for user in orm.MyProjectUser.objects.filter(groups__name__in=('GroupName1', 'GroupName2')):
user.user_permissions.remove(*permissions)
models = {
...
}
complete_apps = ['users']
symmetrical = True
complete_apps = ['users']
中的用户'是应用名称,位于MyProjectUser类。
答案 1 :(得分:0)
当你创建数据迁移时,不要忘记对你在迁移中以某种方式使用的所有应用使用--freeze
参数,在我的例子中是auth
:
python manage.py datamigration my_app --freeze auth
然后使用orm['auth.User'].objects.all()
代替User.objects.all()
。