Django框架16 /Serializer类中使用request

16、Serializer类中使用request

1、将视图类函数参数传递到序列化器中

  • 视图类代码示例:
class ProjectMilestoneView(APIView):
    """ 里程碑 """

    # @checkLogin
    def get(self, request, *args, **kwargs):
        """
        里程碑展示
        - 参数位置
            - 查询参数
        - 请求参数:
            - page:页码  // 非必填
            - limit:每页的数据量  // 非必填
            - project_id: 1  // 必填
        - 成功返回:
        ```json5
        ```
        - 失败返回:
        ```json5
            {
                "code": 0,
                "msg": "异常信息",
                "data": ""
            }
        ```
        """
        cur_user_name = request.session.get('userName')
        page = request.query_params.get('page')  # 当前页码
        limit = request.query_params.get('limit')  # 每页的数据条数
        project_id = request.query_params.get('project_id', "")  # 项目id

        check_res = page_row_check(page, limit)
        if not check_res:
            return Response(res_message(False, 'page、limit页码格式错误!!!'))
        if not project_id:
            return Response(res_message(False, '缺少必传参数`project_id`'))

        queryset = models.ProjectMilestone.objects.filter(milestone_project_id=project_id).order_by(
            'milestone_create_time')

        ser = serializers.ProjectMilestoneReadSerializer(instance=queryset, many=True, context={"request":request})  # 传递视图类参数
        logger.info(f'{cur_user_name}:查看了项目里程碑列表')

        page_display_list = data_paging(ser.data, page, limit)
        return Response(res_message(True, '项目里程碑列表查询成功', {"total": len(ser.data), 'data': page_display_list}))
  • 序列化器代码示例:
class ProjectMilestoneReadSerializer(serializers.ModelSerializer):
    """ 项目里程碑 """

    milestone_principal_name = serializers.CharField(source='milestone_principal.user_name', read_only=True)
    milestone_principal = serializers.SerializerMethodField()
    milestone_deliverables = serializers.SerializerMethodField()
    parent_task_data = serializers.SerializerMethodField()

    class Meta:
        model = models.ProjectMilestone
        exclude = []
        extra_kwargs = {
            'milestone_start_time': {'format': '%Y-%m-%d'},
            'milestone_end_time': {'format': '%Y-%m-%d'},
            'milestone_create_time': {'format': '%Y-%m-%d %H:%M'},
            'milestone_update_time': {'format': '%Y-%m-%d %H:%M'}
        }


    def get_milestone_principal(self, obj):
        """ 负责人 """
        if obj.milestone_principal:
            return obj.milestone_principal.id
        else:
            return ''

    def get_milestone_deliverables(self, obj):
        """ 交付物信息 """
        deliverables_list = models.ProjectMilestoneDeliverables.objects.filter(deliverable_to_milestone=obj.id)
        all_deliverables_info = []
        for single_obj in deliverables_list:
            all_deliverables_info.append({
                "id": single_obj.id,
                "deliverable_name": '.'.join(single_obj.deliverable_name.split(".")[:-1]),
                "deliverable_update_time": single_obj.deliverable_update_time.strftime("%Y/%m/%d"),
                "file": single_obj.deliverable_name
            })
        return all_deliverables_info

    def get_parent_task_data(self, obj):
        parent_task_url = "http://localhost:" + self.context.get('request').get_port() + reverse('parent_task')   # 获取视图类参数
        try:
            response_result = requests.get(url=parent_task_url, params={"milestone_id": obj.id}).json()
            parent_task_data = response_result.get("data").get("data")
            return parent_task_data
        except Exception as e:
            logger.error(f"查询父任务异常,异常原因为:{str(e)}")
            raise CustomException(f"查询父任务异常,异常原因为:{str(e)}")

2、总结

  • 在视图类中使用context传递:serializers.ProjectMilestoneReadSerializer(instance=queryset, many=True, context={"request":request})
  • 在序列化器中在context中获取:self.context.get('request')
posted @ 2022-12-03 14:25  LBZHK  阅读(116)  评论(0编辑  收藏  举报