REST API的部分响应合约:实现类似GraphQL的字段筛选器
在DRF基础上通过URL查询参数`?fields=id,name,profile.avatar`自动裁剪序列化输出,消除多余数据。 · 难度:入门 · +10XP
按需字段解析器
大型REST API常返回过多字段。本教程创建PartialResponseMixin,从URL参数解析嵌套字段路径(支持点分隔),然后递归修改序列化器的fields属性,只保留请求的字段。同时处理反向关系、只读字段保护以及性能优化(避免N+1查询)。最后对比GraphQL的实现差异,让你无需迁移到GraphQL也能获得前端友好的字段控制。
class PartialResponseMixin:
def to_representation(self, instance):
fields = self.context['request'].query_params.get('fields')
if fields:
allowed = set(fields.split(','))
for field_name in list(self.fields.keys()):
if field_name not in allowed:
self.fields.pop(field_name)
return super().to_representation(instance)