自定制过滤器与封装Response对象
基于django-filter扩写 1 写一个类MyFilter,继承BaseFilterBackend 2 重写filter_queryset方法,在该方法内部进行过滤(自己设置的过滤条件) 3 返回queryset对象(过滤后的queryset对象) 4 配置在视图类中 filter_backends = [MyFilter,]
1 以后都使用自己封装的response
from rest_framework.response import Response # 第一种 class APIResponse(Response): def __init__(self, code=100, msg='成功', status=None, headers=None, **kwargs): res_data = { 'code': code, 'msg': msg, } if kwargs: res_data.update(kwargs) super().__init__(data=res_data, status=status, headers=headers) ''' return APIResponse() # 成功,没有数据 { "code": 100, "msg": "成功" } return APIResponse(result=[]) { "code": 100, "msg": "成功" result:[] } return APIResponse(token='xxxxx') { "code": 100, "msg": "成功" token:'xxxxx' } return APIResponse(headers={name:amgl}) # 响应头中会多name=amgl { "code": 100, "msg": "成功" } ''' # 第二种 # class MyResponse(): # def __init__(self): # self.status=100 # self.msg='成功' # @property # def get_dict(self): # return self.__dict__ # if __name__ == '__main__': # res=MyResponse() # res.status=101 # res.msg='查询失败' # # res.data={'name':'AAA'} # print(res.get_dict) # {'status': 101, 'msg': '查询失败'}
from rest_framework.response import Response
# 第一种
class APIResponse(Response):
def __init__(self, code=100, msg='成功', status=None, headers=None, **kwargs):
res_data = { 'code': code, 'msg': msg, }
if kwargs: res_data.update(kwargs)
super().__init__(data=res_data, status=status, headers=headers) '''
return APIResponse() # 成功,没有数据 { "code": 100, "msg": "成功" }
return APIResponse(result=[]) { "code": 100, "msg": "成功" result:[] }
return APIResponse(token='xxxxx') { "code": 100, "msg": "成功" token:'xxxxx' }
return APIResponse(headers={name:amgl}) # 响应头中会多name=amgl { "code": 100, "msg": "成功" } '''# 第二种
# class MyResponse():
# def __init__(self):
# self.status=100# self.msg='成功'
# @property # def get_dict(self):
# returnself.__dict__ # if __name__ == '__main__':
# res=MyResponse() # res.status=101# res.msg='查询失败'
# # res.data={'name':'AAA'} # print(res.get_dict) # {'status': 101, 'msg': '查询失败'}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南