Django view.py,如何在返回响应之前从嵌套字典中删除一个项目?

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

目前我在 view.py 中有一个函数处理来自 React 的 POST 请求。我想在将响应发送回 React 之前从嵌套字典中删除一个项目。

我的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)

console.log 在我的前端的响应是这样的:

{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

我真的很想在将响应发送回 React 之前删除 "created_at"。我尝试了很多方法,例如.pop() & del。但没有运气。有人知道怎么做吗?

解决方案 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)

这会起作用。

方案二。 将模型 created_at 更新为 auto_now_add = True 并在您的序列化程序中删除 created_at 字段。

这也行。