Home > database >  Save query string data using rest framework in Django
Save query string data using rest framework in Django

Time:08-31

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"

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.

CodePudding user response:

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.

  • Related