0

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 ViewSet but picking different Serializers from 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?

2
  • 2
    I'm wondering if this isn't Django anti pattern ? see here Commented May 10, 2021 at 20:54
  • @ChihebNexus Yes, you're correct. The reason is laid out in this statement: 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. Commented May 10, 2021 at 22:12

1 Answer 1

3

You can't achieve what you want, using two different views for the same route is impossible.

However, if the only thing changing between your two viewsets is the serializer, just use the method get_serializer_class.

class YourViewset(viewsets.ModelViewSet):
    # Your attributes ....

    def get_serializer_class(self):
        if self.request.header['flag'] is True: # your condition
            return Type1Serializer
         return Type2Serializer

Sign up to request clarification or add additional context in comments.

2 Comments

This is the way to go OP. If you want 2 vastly different services on the same endpoint, you'll have to put that logic into the action itself, using a if condition and 2 different serializers. Even more so because URLs are generated at launch, so you kind have no choice.
also you will lose the auto swagger schema generation using this approach, if you are using drf_yasg or similar

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.