Returning JSON Response in Django

admin

Administrator
Staff member
I'm attempting to return a JSON response from a query. I've seen examples such as (<a href="https://rayed.com/wordpress/?p=1508" rel="nofollow noreferrer">https://rayed.com/wordpress/?p=1508</a>), 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

Code:
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

Code:
def APCChart(request):
   apcdata = APCPlats.objects.all()
   apcchart = serializers.serialize('json', apcdata)

   return render(request, 'apc.html', JsonResponse(apcchart, safe=False))

<strong>Solution:</strong>

Create the following class:

Code:
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:

Code:
json_data = json.dumps(queryset, cls=DecimalJSONEncoder)

Make sure you import the following:

Code:
from django.core.serializers.json import DjangoJSONEncoder