serialize datetime to json in Django


Question

Hi how do i get DateTimeField from mysql database in django in json format. I got an error when i executed the code 'Date.time cannot be serialized in json'(data holds a lot of values)

data = json.dumps(data)

but this was fixed by adding

ALL_data = serializers.serialize("json", data, ensure_ascii=False)

But now i get 'str' object has no attribute '_meta'

1
21
6/7/2011 2:46:00 PM

Accepted Answer

This solved my problem.

import json
from django.core.serializers.json import DjangoJSONEncoder
data =  json.dumps(data, cls=DjangoJSONEncoder)
77
5/24/2016 1:23:14 PM

Django's serializers are only meant to be used on query sets; you will have to find a different way to solve your problem, such as converting the datetime to something else first.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon