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