python - Request multiple ids from Django REST framework API -


i'm trying make web app api. want make api request multiple ids can submitted.

the django rest framework tutorial shows how records model. example http://127.0.0.1:8000/snippets/ return snippet records. tutorial shows how retrieve single item model. http://127.0.0.1:8000/snippets/2/ return snippet record pk=2.

i'd able request multiple records, not records.

how change code request multiple snippets?

snippets/urls.py

from django.conf.urls import url snippets import views  urlpatterns = [     url(r'^snippets/$', views.snippet_list),     url(r'^snippets/(?p<pk>[0-9]+)/$', views.snippet_detail), ] 

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) 

based in comment, send ids via url:

127.0.0.1:8000/snippets/?ids=2,3,4 

and in view

... ids = request.get.get('ids')  # u'2,3,4' <- unicode ids = ids.split(',')  # [u'2',u'3',u'4'] <- list of unicodes ids values 

then can query snippet model:

snippet.objects.filter(pk__in=ids) 

this give problems if there's spaces between ids in url:

127.0.0.1:8000/snippets/?ids=2, 3 , 4 

you need process every value before perform query


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -