Reputation: 391
I want to create an API, so that when an user requests certain type of data, I want to query database, and create an HTML based on that data and return it in side JSON.
I'm pretty new to the django and the rest framework, but I already learned how to create basic API that serializes the model and returns it. Now I want to do something before returning the data.
result will possibly look like this:
{
"html_response": "<table> (table based on the data) </table>"
}
Upvotes: 1
Views: 348
Reputation: 23024
Given you want to return a fairly customized response, it may be best to extend APIView
directly, override get()
and create the JSON that way. That would give you some flexibility, as opposed to trying to do the same thing with ModelViewSet
s and Serializer
s which are better suited to serializing out specific fields on the model.
For example, if your model was called MyModel
and had an attribute called value
, the following would create a table with a single column with each row holding value
:
from rest_framework import views
from rest_framework.response import Response
class MyEndPoint(views.APIView):
def get(self, request):
table = ['<table>']
for rec in MyModel.objects.all():
table.append('<tr><td>{}</td></tr>'.format(rec.value))
table.append('</table>')
return Response({'html_response': ''.join(table)})
You'd need to then wire that up in your urls.py
:
path('^html_table', myapp.views.MyEndPoint.as_view())
More information on creating views with APIView
can be found here
Upvotes: 1