You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Django REST Framework默认Response类?

解决Django REST Framework自定义默认Response类的问题

DRF确实没有全局的DEFAULT_RESPONSE_CLASS配置项,但可以通过以下几种实用方式实现自定义Response类的复用:

1. 自定义基类视图,统一指定response_class

先编写你的自定义Response类,比如添加统一返回格式的逻辑:

from rest_framework.response import Response

class CustomResponse(Response):
    def __init__(self, data=None, status=None, template_name=None, headers=None, exception=False, content_type=None):
        # 自定义返回结构示例
        wrapped_data = {
            'code': status if status else 200,
            'msg': 'success' if not exception else 'error',
            'data': data
        }
        super().__init__(wrapped_data, status, template_name, headers, exception, content_type)

然后创建基类视图,所有业务视图都继承这个基类:

from rest_framework.views import APIView

class BaseAPIView(APIView):
    response_class = CustomResponse

# 业务视图直接继承基类即可
class UserInfoView(BaseAPIView):
    def get(self, request):
        return self.response_class(data={'username': 'john_doe'})

2. 给视图函数/类直接指定response_class

对于函数视图,使用@api_view装饰器时可以直接声明:

from rest_framework.decorators import api_view

@api_view(['GET'], response_class=CustomResponse)
def hello_view(request):
    return CustomResponse(data={'greeting': 'hello world'})

对于类视图,也可以直接在类中设置属性:

class OrderView(APIView):
    response_class = CustomResponse

    def post(self, request):
        return self.response_class(data={'order_id': '12345'}, status=201)

3. 视图集(ViewSet)中统一配置

如果使用视图集,直接在基类视图集中指定response_class即可:

from rest_framework.viewsets import ModelViewSet

class BaseModelViewSet(ModelViewSet):
    response_class = CustomResponse

# 业务视图集继承基类
class ProductViewSet(BaseModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

以上方法都能让你在项目中统一使用自定义Response类,无需每次手动实例化指定。

内容的提问来源于stack exchange,提问作者Mohamed Nossirat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:59:51