如何使用django rest框架从GET请求的查询参数中过滤多个ID? [英] How to filter for multiple ids from a query param on a GET request with django rest framework?
问题描述
我正在尝试制作一个网络应用程序API。我想提出一个可以提交多个ID的API请求。
I'm trying to make a web app API. I want to make an API request where multiple ids can be submitted.
django rest框架教程显示了如何从模型中获取所有记录。例如, http://127.0.0.1:8000/snippets/ 将返回所有代码段记录。本教程还显示了如何从模型中检索单个项目。 http://127.0.0.1:8000/snippets/2/ 将仅返回具有以下内容的代码段记录pk = 2。
The django rest framework tutorial shows how to get all records from a model. For example http://127.0.0.1:8000/snippets/ will return all snippet records. The tutorial also shows how to retrieve a single item from a model. http://127.0.0.1:8000/snippets/2/ will return only snippet record with pk=2.
我希望能够请求多个记录,但不是所有记录。
I'd like to be able to request multiple records, but not all records.
我怎么能更改此代码,以便我可以请求多个代码段?
How could I change this code so I could request multiple snippets?
snippets / urls.py
snippets/urls.py
from django.conf.urls import url
from snippets import views
urlpatterns = [
url(r'^snippets/$', views.snippet_list),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
]
snippets / views.py
snippets/views.py
def snippet_detail(request, *pk):
try:
snippet = Snippet.objects.filter(pk__in=pk)
except Snippet.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return JSONResponse(serializer.data)
推荐答案
根据您的评论,您可以通过url发送ID:
Based in your comment, you could send the ids via url:
127.0.0.1:8000/snippets/?ids=2,3,4
,并且在您看来
...
ids = request.GET.get('ids') # u'2,3,4' <- this is unicode
ids = ids.split(',') # [u'2',u'3',u'4'] <- this is a list of unicodes with ids values
的Unicode列表,然后您可以查询Snippet模型:
Then you can query to Snippet model:
Snippet.objects.filter(pk__in=ids)
如果url中的id之间有空格,这可能会给您带来一些问题:
This could give you some problems if there's spaces between ids in url:
127.0.0.1:8000/snippets/?ids=2, 3 , 4
您可能需要每个执行查询之前的值
You could need process every value before perform a query
这篇关于如何使用django rest框架从GET请求的查询参数中过滤多个ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!