如何在Django post_保存信号中添加权限?

fquxozlt  于 2022-12-24  发布在  Go
关注(0)|答案(1)|浏览(141)

我在Django post_save信号中添加权限时遇到了问题,因为m2m关系无法持久化。在赋值后,它们正确地显示为user_permissions.all(),但是当我再次保存模型时,查询集变空了。我做错了什么?
如果使用guardian在对象级别分配权限,我就不会遇到同样的问题。

    • 型号. py**
class User(AbstractBaseUser, PermissionsMixin):

    username = models.CharField(db_index=True, max_length=255, unique=True, null=True, blank=True)
    last_name = models.CharField(max_length=255, null=True, blank=True)
    first_name = models.CharField(max_length=255, null=True, blank=True)
    email = models.EmailField(db_index=True, unique=True)    

    def save(self, *args, **kwargs):
        return super(User, self).save(*args, **kwargs)

class Manager(User):
    ...

    def save(self, *args, **kwargs):
        return super(Manager, self).save(*args, **kwargs)
    • 信号. py**
@receiver(post_save, sender=Manager)
def assign_manager_permissions(sender, instance, created, raw, using, **kwargs):

    content_type = ContentType.objects.get_for_model(Manager)
        
    print('Current permissions:')    
    for p in instance.user_permissions.all():
        print(p)

    for codename in ['view_manager',
                         'change_manager',
                         'add_manager',
                         'delete_manager']:

        permission = Permission.objects.get(content_type=content_type, codename=codename)
        instance.user_permissions.add(permission)

    instance.refresh_from_db()
    
    print('After refresh permissions:')
    for p in instance.user_permissions.all():
        print(p)

保存模型时,结果始终相同:

django-1  | Current permissions:
django-1  | 
django-1  | After refresh permissions:
django-1  | user | manager | Can add manager
django-1  | user | manager | Can change manager
django-1  | user | manager | Can delete manager
django-1  | user | manager | Can view manager
mwg9r5ms

mwg9r5ms1#

我通过使用transaction.commit找到了我自己问题的答案,正如所建议的here

from django.db import transaction

def on_transaction_commit(func):
    def inner(*args, **kwargs):
        transaction.on_commit(lambda: func(*args, **kwargs))

    return inner

@receiver(post_save, sender=Manager)
@on_transaction_commit
def assign_manager_permissions(sender, instance, created, raw, using, **kwargs):

    # code here

相关问题