[Answer]-Django: return query result as api

1👍

Here’s a view I use return json, you should be able to adapt it pretty easy:

import json
from django.http import HttpResponse
from django.template.defaultfilters import slugify
from .models import *

def response_times(request):
    response_data = {}  #Create an empty dictionary
    websites = Website.objects.all()  #Query your models
    for site in websites:  
        key = slugify(site.name)
        response_data[key] = {}
        history = History.objects.filter(website=site)[:60]
        response_data[key]['response_times'] = []
        for response in history:
            response_data[key]['response_times'].append({'time': str(response.time), 'timestamp': response.added.strftime('%s')}) 
    return HttpResponse(json.dumps(response_data), content_type="application/json")

0👍

It seems you have in the result QuerySet of some Model instances. So you could specify serializer to work with your model and use it to serialize from model instances to native python data using Rest Framework. Look here for details.

👤mikhdm

Leave a comment