Beispiel #1
0
    def create(self, request, *args, **kwargs):
        """
        添加APP用户

            {
                "id": 1, "groups": [1, 2]
            }
            - id: user的id【必填】
            - groups: 由角色id组成的列表【可选】
        """
        # id必传
        validate_fields(request.data, 'id')
        id = request.data['id']
        group_ids = request.data.get('groups', [])
        user_model = get_user_model()
        user = user_model.objects.get(id=id)
        # 添加用户、角色关联关系
        groups = CustomSerializer.get_instances(Group, group_ids)
        user.groups.clear()
        user.groups.add(*groups)
        # 初始化用户属性
        user.is_in_app = True
        user.is_enable = True
        user.save()
        serializer = self.serializer_class(instance=user)
        return Response(serializer.data)
Beispiel #2
0
 def to_internal_value(self, data):
     """传入参数格式化校验数据"""
     data, no_validated_fields = CustomSerializer.to_internal_value(
         self, data)
     validated_data = super(BasicGroupSerializer,
                            self).to_internal_value(data)
     # 添加多对多关系
     validated_data.update(**no_validated_fields)
     return validated_data
Beispiel #3
0
 def create(self, validated_data):
     """重写创建数据方法"""
     group = Group.objects.create(name=validated_data['name'])
     validated_data.pop('name')
     # 用户ID列表
     user_ids = validated_data.pop('users', [])
     for (k, v) in validated_data.items():
         setattr(group, k, v)
     group.save()
     users = CustomSerializer.get_instances(get_user_model(), user_ids)
     group.user_set.add(*users)
     return group
Beispiel #4
0
    def update(self, request, *args, **kwargs):
        """
        编辑APP用户

            {"groups": [1, 2]}
            - groups: 由id组成的角色列表【可选】
        """
        instance = self.get_object()
        # 判断是否传入groups
        if 'groups' in request.data:
            # 添加用户、角色关联关系
            group_ids = request.data['groups']
            groups = CustomSerializer.get_instances(Group, group_ids)
            instance.groups.clear()
            instance.groups.add(*groups)
        serializer = self.serializer_class(instance=instance)
        return Response(serializer.data)
Beispiel #5
0
 def update(self, instance, validated_data):
     """重写更新数据方法"""
     # users和menus数据单独处理
     if 'users' in validated_data:
         user_ids = validated_data.pop('users')
         users = CustomSerializer.get_instances(get_user_model(), user_ids)
         instance.user_set.clear()
         instance.user_set.add(*users)
     if 'menus' in validated_data:
         menu_ids = validated_data.pop('menus')
         bulk_list = [
             GroupToMenu(group=instance, menu_id=menu_id)
             for menu_id in menu_ids
         ]
         # 先清空多对多关系
         GroupToMenu.objects.filter(group=instance).delete()
         GroupToMenu.objects.bulk_create(bulk_list)
     return super(GroupSerializer, self).update(instance, validated_data)