0

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?

maslak
  • 1,115
  • 3
  • 8
  • 22
  • What you mean by "*pk is not validated as int*"? the **`\d+`** will only match with integers, won't it? – JPG Aug 05 '19 at 06:04
  • That's my workaround. When I use router it allows non digits to pass. – maslak Aug 05 '19 at 06:09

1 Answers1

3

Use lookup_value_regex attribute as,

class UserViewSet(ViewSet):
    lookup_value_regex = '\d+'
    ...
JPG
  • 82,442
  • 19
  • 127
  • 206