我正在以编程方式使用Django群组和权限,并且感到困惑。
将用户添加到组时,也会添加该组的权限。但是,当我从组中删除用户时,该组的权限也被不删除。
以下是一些代码:
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
User = get_user_model()
user_ct = ContentType.objects.get_for_model(User)
group, _ = Group.objects.get_or_create(name="MyGroup")
permission, _ = Permission.objects.get_or_create(content_type=user_ct, codename="my_permission", name="My Permission")
permission_name = f"{permission.content_type.app_label}.{permission.codename}"
group.permissions.add(permission)
group.user_set.add(user)
assert group in user.groups.all()
# THIS WORKS...
assert permission_name in user.get_group_permissions()
group.user_set.remove(user)
assert group not in user.groups.all()
# THIS FAILS...
assert permission_name not in user.get_roup_permissions()
尽管已成功删除该组,但仍保留了关联的权限。
关于我错了什么的任何想法吗?