Home > Back-end >  Django view.py, how to remove an item from a nested dict before returning the response to react?
Django view.py, how to remove an item from a nested dict before returning the response to react?

Time:04-20

Currently I have a function in view.py handling POST request from react. I want to remove an item from a nested dict before sending the reponse back to react.

My view.py:

@api_view(['GET', 'POST'])
def TableViewList(request):
    
    if request.method == 'POST':
        serializer = TabelSerializer(data=request.data)
        
        if serializer.is_valid():
            
            serializer.save()
            
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The response from console.log on my frontend is like this:

{data: {…}, status: 201, statusText: 'Created', headers: {…}, config: {…}, …}
config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data: {id: 121, position: 'Position 3', defect: 'Defect 3', tool: 'Tool 3', created_at: '2022-04-19T03:10:55.724869Z'}
headers: {allow: 'POST, GET, HEAD', content-length: '113', content-type: 'application/json', cross-origin-opener-policy: 'same-origin', date: 'Tue, 19 Apr 2022 03:10:55 GMT', …}
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 201
statusText: "Created"
[[Prototype]]: Object

I really want to delete the "created_at" before sending the reponse back to the react. I have tried many ways, such as, .pop() & del. But no luck. Do anybody know how to do it?

CodePudding user response:

Solution 1.

@api_view(['GET', 'POST'])
def TableViewList(request):
    if request.method == 'POST':
        serializer = TabelSerializer(data=request.data)
        
        if serializer.is_valid():            
            serializer.save()
            data = serializer.data # changed here
            del data['created_at'] # changed here

            return Response(data, status=status.HTTP_201_CREATED) # changed here
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

This will work.

Solution 2. Update your model created_at with auto_now_add = True and in your serializer remove created_at field.

This will work too.

  • Related