[英]Django - Object of type Decimal is not JSON serializable and convert to model data in views
[英]Creating views for a Django application to return object data as JSON & JSONP
我正在嘗試為django應用程序創建視圖以利用我之前創建的模型。 這些模型是世界各大洲/國家/地區,其視圖旨在返回被稱為字符串的數據。
調用這些視圖以返回JSON / JSONP格式的數據,以及與單個國家或地區有關的數據。
我正在嘗試首先為單個國家/地區創建視圖,但是我不確定我在做什么是否完全正確。
def country_json(請求,lander_code,country_code):
country = Country(code = country_code)
country.save()
obj = json.dumps(country.__dict__)
return HttpResponse(obj, content_type="application/json")
我必須找出一種方法來檢查是否必須以JSON / JSONP的形式返回,但是我認為通過查看請求(檢查請求是否具有回調?)應該有點簡單,但是我不確定是否要現在,即使在此階段我想要實現的目標,我也能在這里工作。
一個國家的模型看起來像
class Country(models.Model):
name = models.CharField(max_length=60, default='', unique=True)
code = models.CharField(max_length=3, default='', unique=True)
continent = models.ForeignKey(Continent, default='', related_name='countries')
def __init__(self):
self.area = models.PositiveIntegerField(default=0)
self.population = models.PositiveIntegerField(default=0)
self.capital = models.CharField(max_length=60, default='')
def __str__(self):
return '%s %s %s %s %s %s' % (self.name, self.code, self.capital, self.population, self.area, self.continent)
class Meta:
ordering = ["name"]
verbose_name_plural = "countries"
該視圖應返回的json / jsonp看起來像這樣(示例)
json:
{
"area": 337030,
"population": 5244000,
"capital": "Helsinki"
}
jsonp:
myCallbackFunction({
"area": 337030,
"population": 5244000,
"capital": "Helsinki"
})
有沒有確定的方法可以測試我的視圖如何工作,看看它試圖返回什么樣的數據?
這是我要達到的目標的一個好的開始,還是有一些錯誤的/錯誤的做法?
編輯:
該視圖似乎或多或少地適用於單個國家/地區JSON,但是如果需要,現在我必須添加另一個分支將其轉換為JSONP。
def country_json(request, continent_code, country_code):
all_countries = Country.objects.all()
for country in all_countries:
if country.code == country_code:
area = country.area
population = country.population
capital = country.capital
dictionary = dict([('area', area), ('population', population), ('capital', capital)])
obj = json.dumps(dictionary, indent=4)
return HttpResponse(obj, content_type="application/json")
這對於JSON和JSONP均適用,但是除了專門為此構建的測試功能之外,我沒有很好的方法對其進行測試。
from django.http import Http404
from django.http import HttpResponse
from django.http import JsonResponse
import json
from .models import Continent, Country
def continent_json(request, continent_code):
all_continents = Continent.objects.all()
my_dictionary = {}
for continent in all_continents:
if continent.code == continent_code:
for country in continent.countries.all():
my_dictionary[country.code] = country.name
response = JsonResponse(my_dictionary)
response.status_code = 200
callback = request.GET.get('callback')
if not callback:
return HttpResponse(response, content_type="application/json")
response = '{0}({1})'.format(callback, response)
return HttpResponse(response, content_type="application/javascript")
raise Http404("Not implemented")
def country_json(request, continent_code, country_code):
all_countries = Country.objects.all()
for country in all_countries:
if country.code == country_code:
if country.continent.code == continent_code:
area = country.area
population = country.population
capital = country.capital
dictionary = dict([('area', area), ('population', population), ('capital', capital)])
obj = json.dumps(dictionary, indent=4)
response = JsonResponse(dictionary)
response.status_code = 200
callback = request.GET.get('callback')
if not callback:
return HttpResponse(response, content_type="application/json")
response = '{0}({1})'.format(callback, response)
return HttpResponse(response, content_type="application/javascript")
raise Http404()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.