I've tried to serialize QuerySet
or Dict
object with datetime.date
object in the following ways:
Way #1:
json.dumps(MyModel.objects.values())
Raises error:
Exception Value: [{'date': datetime.date(2012, 5, 26), 'time': datetime.time(0, 42, 27)}] is not JSON serializable
Way #2:
json.dumps(MyModel.objects.values(), cls=DjangoJSONEncoder)
Also raises error:
Exception Value: [{'date': datetime.date(2012, 5, 26), 'time': datetime.time(0, 42, 27)}] is not JSON serializable
Way #3:
json.dumps(MyModel.objects.all(), cls=DjangoJSONEncoder)
Exception Value: [< MyModel: MyModel object>] is not JSON serializable
Way #4:
serializers.serialize('json', MyModel.objects.all())
Raises error:
Exception Value: 'str' object has no attribute '_meta'
How to serialize object with datetime's field to JSON in Django?
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 serializers
output = 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 DjangoJSONEncoder
json.dumps(mydict, cls=DjangoJSONEncoder)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With