0

I am using Django REST Framework and I want to fetch the two parameters entered in the URL.

My URL is:

http://127.0.0.1:8000/api/v1/colleges/slug2/courses/sug1/

where 'slug2' and 'sug1' are the two slug parameters entered.

I want to retrieve those two parameters in my ModelViewSet

views.py

class CollegeCourseViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Course.objects.all()
    lookup_field = 'slug'

    def get_serializer(self, *args, **kwargs):
        if self.action == 'retrieve':
            slug1 = self.kwargs.get('slug1')
            slug2 = self.kwargs.get('slug2')
            print(slug2)
            queryset = Course.objects.filter(slug=slug2)
            return Response(CollegeCourseSerializer(queryset, many=True).data, status=status.HTTP_200_OK)

urls.py

router = routers.DefaultRouter()

router.register(r'courses', CollegeCourseViewSet, basename='college_course_list')

urlpatterns = [
    path('api/v1/colleges/<slug:slug>/', include(router.urls)),
]

But slug2 outputs None and hence the problem.

Is there any specific way to obtain those parameters.

Thanks in advance.

Shreyas Shetty
  • 618
  • 6
  • 13

2 Answers2

0

Try this

def get_serializer(self, *args, **kwargs):
        if self.action == 'retrieve':
            slug1 = self.kwargs.get('slug1') 
            slug2 = self.kwargs.get('slug2')
            queryset = Course.objects.filter(slug2=slug2)
            return Response(CollegeCourseSerializer(queryset, many=True).data, status=status.HTTP_200_OK)

In your urls.py, I am only seeing 1 slug being passed i.e slug not slug1. So, if you want to parse another slug then you might need to add that in your URLs and then parse it in the view. If you want your URL to look like this

http://127.0.0.1:8000/api/v1/colleges/slug2/courses/slug1/

Then you have to change your urls.py to

 path('api/v1/colleges/<slug:slug2>/course/<slug:slug1>/', include(router.urls)),
Dharman
  • 30,962
  • 25
  • 85
  • 135
SDRJ
  • 532
  • 3
  • 11
0

Actually I was trying to retrieve the slug of the lookup_field as well in the params. But it is related to model and not a parameter, rightly pointed out in the comments.

So I just accessed it by the lookup_url_kwarg field in the ModelViewSet.

For more details refer : this answer

Shreyas Shetty
  • 618
  • 6
  • 13