Django serialize datetime to json in QuerySet/Dict Django serialize datetime to json in QuerySet/Dict json json

Django serialize datetime to json in QuerySet/Dict


Your issue has nothing to do with datetimes. It's simply that querysets are not by themselves directly serializable, even with the DjangoJSONEncoder class and even using values(). You'll get exactly the same result with a model with no datetime fields at all.

The way you're supposed to do serialization in Django is to use serializers:

from django.core import serializersoutput = serializers.serialize('json', MyModel.objects.all())

But no doubt you're trying to avoid that because the output format is so unnecessarily complex. Instead, I usually use the 'python' serializer to convert to a dict, then dump to json:

temp_output = serializers.serialize('python', MyModel.objects.all())output = json.dumps(temp_output, cls=DjangoJSONEncoder)


If you want to just dump a dictionary to JSON, just use json.dumps. It can easily be made to serialize objects by passing in a custom serialization class - there's one included with Django that deals with datetimes already:

from django.core.serializers.json import DjangoJSONEncoderjson.dumps(mydict, cls=DjangoJSONEncoder)


This is the way i have retrieved datetime in json format,

from django.core import serializers_data = serializers.serialize('json', MyModel.objects.all())bi_data = [i.get('fields', i) for i in json.loads(_data) if i]