cameron-f cameron-f - 5 months ago 53
Python Question

Request multiple ids from Django REST framework API

I'm trying to make a web app API. I want to make an API request where multiple ids can be submitted.

The django rest framework tutorial shows how to get all records from a model. For example will return all snippet records. The tutorial also shows how to retrieve a single item from a model. 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?


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),


def snippet_detail(request, *pk):
snippet = Snippet.objects.filter(pk__in=pk)
except Snippet.DoesNotExist:
return HttpResponse(status=404)

if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return JSONResponse(


Based in your comment, you could send the ids via url:,3,4

and in your view

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

Then you can query to Snippet model:


This could give you some problems if there's spaces between ids in url:, 3 , 4

You could need process every value before perform a query