|
|
from rest_framework.serializers import ModelSerializer, Serializer, IntegerField, BooleanField
|
|
|
from .permission_serializer import PermissionsSerializer
|
|
|
from erp_system.models import RolesModel, PermissionsModel
|
|
|
from rest_framework import serializers
|
|
|
|
|
|
|
|
|
class RolesSerializer(ModelSerializer):
|
|
|
"""
|
|
|
普通的序列化
|
|
|
"""
|
|
|
permissions = PermissionsSerializer(many=True, read_only=True)
|
|
|
delete_flag = serializers.CharField(read_only=True)
|
|
|
|
|
|
class Meta:
|
|
|
model = RolesModel
|
|
|
fields = '__all__'
|
|
|
|
|
|
|
|
|
class RolesPartialSerializer(ModelSerializer):
|
|
|
"""
|
|
|
给一个角色批量授权的序列化器。
|
|
|
"""
|
|
|
|
|
|
class Meta:
|
|
|
model = RolesModel
|
|
|
fields = ['id', 'permissions']
|
|
|
|
|
|
def save(self, **kwargs):
|
|
|
# 针对某一个角色批量授权,之前存在的不变,之前没有的会增加权限
|
|
|
if self.instance:
|
|
|
permission_list = self.validated_data.get('permissions')
|
|
|
current_list = self.instance.permissions.all()
|
|
|
|
|
|
if permission_list:
|
|
|
for p in permission_list:
|
|
|
if p not in current_list:
|
|
|
# 多对多的关联 如果数据库中已经存在对象,则使用add,否则使用
|
|
|
# 变量名=变量名.B类名小写_set.create(字段='值')
|
|
|
self.instance.permissions.add(p.id)
|
|
|
|
|
|
self.instance.save()
|
|
|
return self.instance
|
|
|
|
|
|
|
|
|
class RoleSetPermissionSerializer(Serializer):
|
|
|
"""
|
|
|
角色单一授权,或者取消单一授权
|
|
|
"""
|
|
|
# 角色ID
|
|
|
role_id = IntegerField(write_only=True, required=True, help_text='选择的角色ID')
|
|
|
permission_id = IntegerField(write_only=True, required=True, help_text='选择的权限ID')
|
|
|
# 是否是:取消授权还是授予权限
|
|
|
is_create = BooleanField(write_only=True, required=True, help_text='是否授予还是删除权限')
|