How to change url params (query_string) in django rest framework before handle request?

Because I need compatible with old client. For example, when I recevie an request http://0.0.0.0:8000/api/exercises/?pk=13, i want change the params so http://0.0.0.0:8000/api/exercises/?id=13.

Others: http://0.0.0.0:8000/api/exercises/?displayName=ABC change to http://0.0.0.0:8000/api/exercises/?display_name=ABC

http://0.0.0.0:8000/api/exercises/?target=1,2 change to http://0.0.0.0:8000/api/exercises/?target=1&target=2

Is there any place I can write code before handle the request? I try to change request.environ['QUERY_STRING'] and request.META['QUERY_STRING'] in middleware, but not work.

Thanks.

You can use django's redirect function for this. For that in your old views just redirect it to your new views.

A simple Example -

def my_old_view(request,pk):
    ...
    return redirect(f'/api/excersise/?id={pk}')

So if someone enters your old URL it will be redirected to new one without any issues.

I believe you can make use of the RedirectView and override the get_redirect_url method to map the change in query params.

For implementation details, you can refer to the official docs.

Good luck!

Back to Top