Change the parent lookup kwarg in nested routes using Django REST Framework

131 views Asked by At

In this project we use Django, Django REST Framework, DRF Nested Routers and DRF Spectacular.

Let's say that we have the model classes Category and Product.

We have a nested route:

  • /categories/<category_pk>/products/<pk>/

In the Swagger UI (generated by DRF Spectacular) it is displayed as:

  • /categories/{category_pk}/products/{id}/

I want to change the parent lookup keyword argument to be category_id, but I couldn't find a way to do it.

1

There are 1 answers

0
cezar On

The solution is very simple, but you have to look at the right place. I was trying to set it in ProductViewSet with parent_lookup_kwargs, and similarly in the serializers. But that didn't help.

I added lookup_url_kwarg in the CategoryViewSet and it works like a charm:

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    lookup_url_kwarg = "id"

Otherwise Django REST Framework defaults to "pk". DRF Spectacular changes it to {id} in the Swagger UI.
But for the nested routes it can't change the composed name category_pk. The lookup_url_kwarg set to "id" did the trick.