Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with URL arguments in Django REST Frameworks

I am new to Django REST Frameworks and despite doing the tutorial twice and reading lots of documentation I can't work out exactly how to handle/access the arguments in a URL in the DRF ViewSet.

My URL looks like this:

/api/v1/user/<user-id>/<age>/update

In my base urls.py I have the urlpattern:

url(r'^api/v1/', include('api.urls'))

In the api/urls.py I have:

from django.conf.urls import url, include
from rest_framework import routers
from api import views

router = routers.DefaultRouter()
router.register(r'user', views.UserViewSet)	

urlpatterns = [
    url(r'^', include(router.urls))
]

My question is what should my UserViewSet look like to handle the url, extract the user id and age fields, and update the UserDetails model so the given user has the given age?

My model hasn't been created yet but will look something like this:

class UserDetails(models.Model):
    user = models.ForeignKey(User)
    age = models.BigIntegerField(blank=True, null=True)
like image 706
Bill Noble Avatar asked Oct 31 '22 19:10

Bill Noble


1 Answers

In the serializers.py adde the ParameterisedHyperlinkedIdentityField as a serializer.

serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    url = ParameterisedHyperlinkedIdentityField(view_name='user-detail', lookup_fields=(('id', 'id'), ('age', 'age')), read_only=True)

    class Meta:
        model = UserDetails

urls.py

from .viewsets import UserViewSet
user_list = UserViewSet.as_view({'get':'list'})
user_detail = UserViewSet.as_view({'get':'retrieve'})

urlpatterns= [
    url(r'^user/(?P<id>\d+)/(?P<age>[-\w\d]+)/update/$', user_detail, name='user-detail')

]

viewsets.py

class UserViewset(viewsets.ModelViewSet):
    lookup_field = 'id'
    serializer_class = UserSerializer
    queryset = UserDetails.objects.all()
like image 64
Seenu S Avatar answered Nov 15 '22 05:11

Seenu S