在我看来,应该有一种自动方式来查询 Django Rest Framework 调用的结果并像字典(或类似的东西)一样操作它。我错过了什么,还是不可能?
即,
如果调用http://localhost:8000/api/1/roles/
产量
{"count": 2, "next": null, "previous": null, "results": [{"user": {"username": "smithb", "first_name": "Bob", "last_name": "Smith"}, "role_type": 2, "item": 1}, {"user": {"username": "jjones", "first_name": "Jane", "last_name": "Jones"}, "role_type": 2, "item": 1}]}
我认为类似于http://localhost:8000/api/1/roles/0/user/username
的东西应该返回smithb
。
此功能是否存在或者我需要自己构建它吗?
最佳答案
这似乎是你必须自己构建的东西。也就是说,Django 让这种事情变得非常容易。在 URLS 中,您可以指定要传递给 View 的 url 路径的一部分。您可以使用正则表达式捕获值,然后将它们传递到您的 View 函数中。
Urls:
url(regex=r'^user/api/1/roles/(?P<usernumber>\w{1,50})/(?P<username>\w{1,50})/$', view='views.profile_page')
a request for http://domain/user/api/1/roles/0/username/
View:
def someApiFunction(request, usernumber=None ,username=None):
return HttpResponse(username)
一些额外的资源:
https://docs.djangoproject.com/en/1.7/intro/tutorial03/#writing-more-views
Capturing url parameters in request.GET
关于python - djangorest框架查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24288411/