drf-nested-routers
drf-nested-routers copied to clipboard
Change the URL parameter names?
I suspect this is a silly question that I could answer myself if I could find the right parts of the docs. So sorry in advance about that.
I want to have my URLs be more explicit about the path params. This is mostly for people reading the auto generated swagger docs.
I'd like my URLs to look like this:
/node/
/node/{node_id}/
/node/{node_id}/disk/
/node/{node_id}/disk/{disk_id}/
The closest I can get is:
/node/
/node/{node_id}/
/node/{node_node_id}/disk/
/node/{node_node_id}/disk/{disk_id}/
I get this far by setting the lookup field in my NodeViewSet to 'node_id', in DiskViewSet it's 'disk_id'.
My router then looks like this:
router = routers.SimpleRouter()
router.register(r"node", views.NodeViewSet, base_name="node")
node_router = routers.NestedSimpleRouter(router, r"node", lookup="node")
node_router.register(r"disk", views.DiskViewSet, base_name="node-disk")
How can I get rid of that pesky 'node_' prefix? Thanks!
If you look in the source, the nested router classes include some info on the lookup
argument:
lookup:
The regex variable that matches an instance of the parent-resource
will be called '<lookup>_<parent-viewset.lookup_field>'
In the example above, lookup=domain and the parent viewset looks up
on 'pk' so the parent lookup regex will be 'domain_pk'.
Default: 'nested_<n>' where <n> is 1+parent_router.nest_count
Basically there will always be two strings separated by an underscore (see routers.py line 53)
In your case the Viewset's lookup_field
is likely node_id
, which when combined with the router's lookup='node'
results in that node_node_id
string 🙂
The question is how do you fix i.e. change this!?
Hi @matthewsheeran.
I think that your question is similar to the one on #270, yet idk if is a duplicate. Anyway, there I dug over why stuff is like that. You can read more here: https://github.com/alanjds/drf-nested-routers/issues/270#issuecomment-1204155795
Hope this to helps to understand how and why things are as they are today, yet any change proposal will be very welcome from my side :+1:
Best regards.
Yeah i tried changing things in the NestedMixin etc code but only succeeeded breaking things as you cautioned. I then looked at only modifying the Swagger UI from drf-spectacular - which was the real issue - along the lines of https://github.com/tfranzel/drf-spectacular/pull/516 . Not exaclty per this post but something similar for drf-yasg with their respective SchemaGenerator and OpenAPISchemaGenerator being customized which sounds more promising for my purposes.. Ah here it is: https://github.com/alanjds/drf-nested-routers/issues/180