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

Time:11-17

I am trying to add more fields to the Response in the django rest framework to send to react frontend.

This works fine

@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)

How can I add the json context below to the Response also?

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

CodePudding user response:

You can add the extra data with:

@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({**context, **response_data.data}, status=status.HTTP_201_CREATED)
  • Related