我试图从查询中返回JSON响应。我已经看过(https://rayed.com/wordpress/?p=1508)等示例,但他们没有通过HTML模板。我收到错误" ictionary update sequence element#0的长度为510; 2是必需的"
模型
class APCPlats(models.Model):
PlatsProjected = models.IntegerField(db_column='Projected', blank=True, null=True)
PlatsCompleted = models.IntegerField(db_column='Complete', blank=True, null=True)
Month = models.CharField(db_column='Month', max_length=200 , blank=True, null=True)
def __str__(self):
return self.Month
class Meta:
managed = True
db_table = 'APCPlats'
查看
def APCChart(request):
apcdata = APCPlats.objects.all()
apcchart = serializers.serialize('json', apcdata)
return render(request, 'apc.html', JsonResponse(apcchart, safe=False))
解决方案:
创建以下类:
class DecimalJSONEncoder(json.JSONEncoder):
def default(self, o):
if type(o) == Decimal:
# Here You can decide if You want decimal to be converted
# to string or float.
return float(o)
if isinstance(o, datetime.datetime):
#return o.replace(tzinfo=None).isoformat()
return datetime.datetime.strftime(o, "%Y/%m/%d")
return super(DecimalJSONEncoder, self).default(o)
如何在查询集上使用该类:
json_data = json.dumps(queryset, cls=DecimalJSONEncoder)
确保导入以下内容:
from django.core.serializers.json import DjangoJSONEncoder
答案 0 :(得分:1)
我知道您正在尝试使用ajax将查询集返回到前端。如果是这种情况,你不需要渲染,你需要的只是Jsonresponse:
return JsonResponse(appchart, safe=False)