我有一个包含特定权限的 Django 模型。我希望能够将权限分配给assigned_to field
. 我django-guardian
用来管理权限。
from django.db import models
from django.contrib.auth.models import User
from guardian.shortcuts import assign_perm
class Project(models.Model):
...
assigned_to = models.ManyToManyField(
User, default=None, blank=True, null=True
)
created_by = models.ForeignKey(
User,
related_name="%(app_label)s_%(class)s_related"
)
permissions = (
('view_project', 'View project'),
)
我试图实现自定义保存方法。如果我在保存之前尝试这样做:
def save(self, *args, **kwargs):
for user in self.assigned_to:
assign_perm('view_project', user, self)
super(Project, self).save(*args, **kwargs)
我收到一个错误:
ObjectNotPersisted: Object <project_name> needs to be persisted first
如果我在保存后这样做(无论如何我猜这是错误的):
def save(self, *args, **kwargs):
super(Project, self).save(*args, **kwargs)
for user in self.assigned_to:
assign_perm('view_project', user, self)
我得到一个Type Error 'ManyRelatedManager' object is not iterable
.
我应该post-save
为此使用信号吗?对于我认为常见的模式,最好的方法是什么?