1

I have an application with an API created with DRF. In that i use a DRF-router to route the URL's. I want to add a route to the list-view with parameters (so @list_route won't work) to certain viewsets, but not to others.

So i wanted to define two routers:

user_router = routers.SimpleRouter()
admin_router = routers.SimpleRouter()

I want a route added to one of them:

search_route = Route(
    url='^{prefix}/search/(?P<field>\w+)/(?P<value>\w+){trailing_slash}$',
    mapping={
        'get': 'search',
    },
    name='{basename}-search',
    initkwargs={}
)

admin_router.routes.append(search_route)

But now i end up with the search_route added to both routers, and thus coupled to the viewsets i register in the routers individually.

ipython> user_router.routes
...
 Route(url='^{prefix}/search/(?P<field>\\w+)/(?P<method>\\w+)/(?P<keyword>\\w+){trailing_slash}$', mapping={'get': 'search'}, name='{basename}-search', initkwargs={'suffix': 'Search'}),
...

Why is this??? I am probably missing something basic here. How can i add a Route() to certain routers but not to others, so that i can split up my API-urls in "user" and "admin" with each their own methods.

1 Answer 1

2

Allright, i figured it out. The SimpleRouter class in the Django Rest Framework defines the routes in the class, and doesn't bind the values in the __init__ phase. SimpleRouter.routes is a list.

Since lists are mutable, all instances of SimpleRouter point at the same route-list when creating the SimpleRouter instances. When i appended a Route to admin_router.routes, it also updated user_router.routes....

The way to overcome this is to define separate Router classes which override the router-list.

class AdminRouter(SimpleRouter):
    routes = # [ ... my list of Route()'s ... ]


class UserRouter(SimpleRouter):
    routes = # [ ... my other list of Route()'s ...]


admin_router = AdminRouter()
user_router = UserRouter()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.