如何在 django rest 框架中向 return 响应添加更多字段

How to add more fields to the return response in django rest framework

我正在尝试向 django rest 框架中的 Response 添加更多字段以发送到反应前端。

这个很好用

@api_view(('GET',))
def get_status(request, task_id):
    task = current_app.AsyncResult(task_id)

    response_data = ImageSerializer(Image.objects.get(pk=task.get()))

    return Response(response_data.data, status=status.HTTP_201_CREATED)

如何将下面的 json context 添加到响应中?

#How can I add the following to my response too
context = {'task_status': task.status, 'task_id': task.id}

您可以通过以下方式添加额外数据:

@api_view(('GET',))
def get_status(request, task_id):
    task = current_app.AsyncResult(task_id)

    response_data = ImageSerializer(Image.objects.get(pk=task.get()))
    context = {'task_status': task.status, 'task_id': task.id}

    return Response(<strong>{**context, **response_data.data}</strong>, status=status.HTTP_201_CREATED)