Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django serialize datetime to json in QuerySet/Dict

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?

like image 548
Deadly Avatar asked May 26 '12 08:05

Deadly


2 Answers

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)
like image 149
Daniel Roseman Avatar answered Sep 17 '22 23:09

Daniel Roseman


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)
like image 33
Sajid Ahmad Avatar answered Sep 17 '22 23:09

Sajid Ahmad