我正在尝试迁移我的模型以使用Guardian权限。在这一点上,我有:
class Data(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Meta:
permissions = (
('view', 'View'),
('edit', 'Edit'),
('owner', 'Owner'),
)
我创建了一个添加了新权限的迁移,在自定义迁移中,我尝试分配如下权限:
def assignDataPermissions(apps, schema_editor):
Data = apps.get_model('api', 'Data')
for data in Data.objects.all():
assign_perm('api.owner', data.user, data)
class Migration(migrations.Migration):
dependencies = [
('api', '0169_auto_20180304_1619'),
]
operations = [
migrations.RunPython(assignDataPermissions)
]
这失败了 guardian.exceptions.NotUserNorGroup: User/AnonymousUser or Group instance is required (got EmailUser object)
.
有没有更好/正确的方法迁移到守护者?如果没有,如何让它看到我的自定义用户类?
我最终使用了更高级别的解决方法。在迁移中,data.user
实际上是__fake.EmailUser
的对象,而get_user_model()
返回custom_user.models.EmailUser
。因此,监护人未通过检查isinstance(identity, get_user_model())
。
我的解决方法(hack?(是从对应于data.user
的数据库中显式获取EmailUser
对象。这样:
def assignDataPermissions(apps, schema_editor):
Data = apps.get_model('api', 'Data')
User = get_user_model()
for data in Data.objects.all():
user = User.objects.get(id=data.user_id)
assign_perm('api.owner', user, data)
通常,在迁移中加载外部库容易出错。
尝试像这样的低级操作:
def assignDataPermissions(apps, schema_editor):
Data = apps.get_model('api', 'Data')
Permission = apps.get_model('auth', 'Permission')
owner_api = Permission.objects.get(content_type__applabel='api', codename='owner')
UserObjectPermission = apps.get_model('guardian', 'UserObjectPermission')
for data in Data.objects.all():
UserObjectPermission.objects.create(permission=owner_api, user=data.user, content_object=data)