from django.http import Http404, HttpResponse from .models import Continent, Country import json def continent_json(request, continent_code): data = Continent.objects.filter(code=continent_code) if len(data) <= 0: raise Http404("Continent not found") countries = {} query = data.first().countries.all() for country in query: countries[country.code] = country.name dump = json.dumps(countries) if request.GET.get("callback") is not None: return HttpResponse(request.GET.get("callback") + "(" + dump + ")") return HttpResponse(dump, content_type="application/json") def country_json(request, continent_code, country_code): data = Continent.objects.filter(code=continent_code) if len(data) <= 0: raise Http404("Continent not found") query = data.first().countries.filter(code=country_code) if len(query) <= 0: raise Http404("Country not found") query = query.first() country = {"area": query.area, "population": query.population, "capital": query.capital} dump = json.dumps(country) if request.GET.get("callback") is not None: return HttpResponse(request.GET.get("callback") + "(" + dump + ")") return HttpResponse(dump, content_type="application/json")