Reputation: 4170
Pending solution but all I'm seeing is that I need to actually create a custom Renderer as per the doc here -
http://django-rest-framework.org/api-guide/renderers
I know this as going by the same data in XML output in the file "renderers.py" there is an XMLRenderer
If I change, using the example below, "list-item" to be the table/model name I get the output I want so I'm going to investigate creating a custom renderer.
I have a json output that looks like this -
{
"trgmst_id": 224,
"trgjob_id": 22652,
"jobmst_id": 10079,
"trgjob_order": 2,
"trgjob_type": 0,
"trgjob_level": 0
}
But instead I want it to look like this -
{
"trgjob": {
"trgmst_id": 224,
"trgjob_id": 22652,
"jobmst_id": 10079,
"trgjob_order": 2,
"trgjob_type": 0,
"trgjob_level": 0
}
}
How do I get my serializer or view to include the model name?
Here is my serializer -
class TrgjobSerializer(serializers.ModelSerializer):
class Meta:
model = Trgjob
Here is my view -
@csrf_exempt
def trgjob_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
DEV = Trgjob.objects.using('database1').filter(jobmst_id=pk)
except Trgjob.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = TrgjobSerializer(DEV, many=True)
return JSONResponse(serializer.data)
And here is the JSONResponse -
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
Upvotes: 0
Views: 68
Reputation: 48952
One option is to construct the desired output in the view. For example
from rest_framework.response import Response
def view(request):
...
serializer = TrgJobSerializer(DEV, many=True)
response = {'trgjob': serializer.data}
return Response(response)
The JSONRenderer will still handle rendering to JSON, e.g. converting False
to false
etc.
Upvotes: 1