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.

3
  • 1
    You're trying to get query parameter using name slug2, but your url patter define only slug argument. Commented Feb 15, 2021 at 14:24
  • I included a lookup_field in the ViewSet so it gives the second slug when entered. Commented Feb 15, 2021 at 14:27
  • 1
    lookup_field related to model field to lookup - > slug field in url, so still you can't get any slug2 here. Commented Feb 15, 2021 at 14:31

2 Answers 2

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)),
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.