简体   繁体   中英

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?

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)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM