I need to use Multiple ViewSets with the same URL where the active ViewSet needs to be selected dynamically based on request header logic. Django rest framework allows you to do this to register the viewsets against different urls:
router.register(r"type_1", Type1ViewSet, basename="type_1")
router.register(r"type_2", Type2ViewSet, basename="type_2")
However, in my case, the viewsets are very similar. So I'd like to do this in the urls.py file:
if request.header['flag'] is True:
router.register(r"type", Type1ViewSet, basename="type_1")
else:
router.register(r"type", Type2ViewSet, basename="type_2")
In my case, the following wouldn't work:
- Using a single
ViewSetbut picking differentSerializersfrom the header logic instead of dealing with multiple ViewSets.
Is there a way to get access to the request object in the urls.py so that I can use it to orchestrate my conditional? If not, how this can be achieved?
URLs are not loaded dynamically for every user, they are parsed and loaded on application startup, so you cannot put per-request logic in there. In general, this logic should be handled in your view.