Validate pk as int in drf viewset retrieve url

1.4k Views Asked by At

Code looks as follows:

class UserViewSet(ViewSet):

    # ... Many other actions
    def list(self):
        # list implementation

    def retrieve(self, request, pk):
        # manual pk int validation

router = DefaultRouter()
router.register(r"users", UserViewSet, basename="users")
urlpatterns = router.urls

Right now pk is not validated as int therefore a request to db is made, which I want to avoid. Is there any way I can add that type of validation in urls? I can achieve that without using router like this:

urlpatterns = [
    path('users/<int:pk>/', UserViewSet.as_view({'get': 'retrieve'}),
    # many other actions have to be added seperately
]

But I have many actions in my viewset and all of them have to be added separately. Is there a cleaner way to do so or a package?

1

There are 1 best solutions below

0
On BEST ANSWER

Use lookup_value_regex attribute as,

class UserViewSet(ViewSet):
    lookup_value_regex = '\d+'
    ...