bluebuddah
bluebuddah

Reputation: 317

Django REST - grab paramater value when part of the URL

I have the following urls.py:

from django.urls import path, include
from rest_framework.routers import DefaultRouter

from location import views

router = DefaultRouter()

router.register('city', views.CityViewSet, 'city')

app_name = 'location'

urlpatterns = [
    path('', include(router.urls)),
]

when hitting the url /api/location/city/25/ I get all the details for that object instance (with the id of 25) as expected.

My question how do I grab the id number in my viewset?

I know how to do it with just regular query parameters /?id=25, but can't seem to figure out how to do it when it's part of the URL.

Upvotes: 1

Views: 30

Answers (1)

heemayl
heemayl

Reputation: 42017

URL captures are available as the kwargs attribute (which is a dict) of the viewset instance. So from inside any viewset method, you can access them via self.kwargs.

In this case, as you're retrieving the instance (GET on detail), you can get the pk (primary key) via:

class CityViewSet(ModelViewSet):
    ...

    def retrieve(self, request, *args, **kwargs):
        pk = self.kwargs['pk']

Note that, I've assumed your lookup_url_kwarg is pk (the default); if you have something different you need to access by that key name as you can imagine.

Upvotes: 2

Related Questions