I'm attempting to return a JSON response from a query. I've seen examples such as (https://rayed.com/wordpress/?p=1508), but they don't incorporate passing the HTML template. I'm receiving an error "ictionary update sequence element #0 has length 510; 2 is required"
Model
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'
View
def APCChart(request):
apcdata = APCPlats.objects.all()
apcchart = serializers.serialize('json', apcdata)
return render(request, 'apc.html', JsonResponse(apcchart, safe=False))
Solution:
Create the following class:
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)
How to use the class on your queryset:
json_data = json.dumps(queryset, cls=DecimalJSONEncoder)
Make sure you import the following:
from django.core.serializers.json import DjangoJSONEncoder