I have set up a Django Rest Framework ModelViewSet
for a Product model. The Product has a uuid4
primary key field. The API list views are working, but I can't access the detail views using the default router, I guess because the uuid4
primary key doesn't fit the pk
integer regex the router expects? The error is a TypeError
in python3.6/site-packages/rest_framework/viewsets.py
:
retrieve() got an unexpected keyword argument 'pk'
From the router documentation, I believe I need a custom router, but I don't understand how to replace the {lookup}
field from an integer pk regex to a uuid4 regex (?P<uuid>[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12})
. I think the relevant part of the source code is here.
My present url config is as follows:
from .views.API.product import ProductViewSet
from django.conf.urls import include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'product', ProductViewSet, base_name='product')
urlpatterns += [
url(r'^API/0.1/', include(router.urls)),
]
simply update your code to something like this:
class ProductViewSet(ModelViewSet):
lookup_field = 'my_uuid_field'
lookup_field
tells DRF to use this field instead of pk
to get items
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With