【Django】rest_framework 序列化自定义替换返回值
# 序列化设置 class PagerSerialiser(serializers.ModelSerializer): name = serializers.CharField(source="society.name") is_pass =serializers.CharField() class Meta: model = models.SocietyAndUser fields = "__all__" class Society(APIView): def get(self, request): data = {} try: s_data = models.SocietyAndUser.objects.filter(user_id=request.auth).order_by('id') for da in s_data: da.is_pass = self.type_t(da.is_pass) pg = PageNumberPagination() pg.max_page_size = 200 pg.page_size_query_param = "size" pager_roles = pg.paginate_queryset(queryset=s_data, request=request, view=self) ser = PagerSerialiser(instance=pager_roles, many=True) data["code"] = 200 data["count"] = len(s_data) data["data"] = ser.data return Response(data) except Exception as e: print(traceback.format_exc()) data["code"] = 444 data["message"] = "请求异常" return JsonResponse(data) def type_t(self,is_pass): data = {False:"正在申请中",True:"已加入社团"} res = data[is_pass] return res
print结果: s_data <QuerySet [<SocietyAndUser: SocietyAndUser object>, <SocietyAndUser: SocietyAndUser object>, <SocietyAndUser: SocietyAndUser object>, <SocietyAndUser: SocietyAndUser object>, <SocietyAndUser: SocietyAndUser object>, <SocietyAndUser: SocietyAndUser object>, <SocietyAndUser: SocietyAndUser object>]> 正在申请中 已加入社团 正在申请中 已加入社团 正在申请中 正在申请中 正在申请中