Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Save query string data using rest framework in Django

I need to save to a database the query string data coming from a GET request using Django Rest framework.

Something like this:

URL: "http://127.0.0.1:8000/snippets/snippets/?longitude=123123&latitude=456456"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    #code here for saving the query string data to database, in this case save: 
    #{
    #"longitude":123123,
    #"latitude":456456
    #}

It’s just like saving the params data like it were a POST request.

>Solution :

I need to save to a database the query string data coming from a GET request using Django Rest framework.

This is against the specifications of the HTTP protocol. Indeed, a GET request should only be used to retrieve data, not update data. For that a POST, PUT, PATCH or DELETE request should be used. The querystring is normally used to filter, not to store data.

If you really want to do this, you can override the .get(…) handler and

# Warning: against the HTTP protocol specifications!
class SnippetCreateView(generics.CreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    # {
    # "longitude":123123,
    # "latitude":456456
    # }
    def get(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(
            serializer.data, status=status.HTTP_201_CREATED, headers=headers
        )

But this is really not a good idea.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading