Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change key of lookup kwargs field in RetrieveAPIView in Django REST Framework?

Django REST Framework uses pk has the lookup field when using the RetrieveApiView and same has to be defined in the url kwargs .

This makes the url look like :

url(r'^(/foobar/(?P<pk>[\d]+)/$', FooBarFetch.as_view(), name="foo_bar")

But I want to replace the pk in the url with something more descriptive like foo_bar_id.

Changing the look_up_field doesn't work as it still has to use the pk to perform the lookup.

Just kwrags key has to be changed in the url.

like image 913
priyankvex Avatar asked Oct 20 '25 15:10

priyankvex


1 Answers

So I dug into the classes GenericAPIView etc and found that it uses a field lookup_url_kwarg for this purpose.

By default, it is None and that makes the kwarg key to be pk in the url.

We just need to override the field like :

lookup_url_kwarg = 'foo_bar_id'

Where foo_bar_id is the key used in url.

like image 167
priyankvex Avatar answered Oct 23 '25 05:10

priyankvex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!