我正在编写我的第一个 REST API(使用 django-rest-framework)。
我正在添加 URL 参数来过滤结果。我的理解是这些参数的文档属于 OPTIONS 动词。我的代码:
class SuburbViewSet(viewsets.ReadOnlyModelViewSet):
"""
Retrieves the suburbs (20 per page).
GET and OPTIONS allowed.
"""
model = Suburb
serializer_class = SuburbSerializer
def get_queryset(self):
"""
Can filter by region_id, ...
- using query parameters in the URL.
"""
queryset = Suburb.objects.all()
region_id = self.request.QUERY_PARAMS.get('region_id', None)
if region_id is not None:
queryset = queryset.filter(region_id=region_id)
return queryset
def metadata(self, request):
ret = super(SuburbViewSet, self).metadata(request)
ret['parameters'] = {
"page": {
"type": "integer",
"description": "The page number",
"required": False
},
"region_id": {
"type": "integer",
"description": "The region ID to filter the results",
"required": False
}
}
return ret
这是最好的/唯一的 REST 方式(解释 OPTIONS 中的参数)吗?
关于 django-rest-framework,我已经扩展了感觉 hacky 的元数据(self,request)。我是否错过了一些设置参数描述的内置方法?
谢谢 !