Django serialize datetime for json in QuerySet / Dict

I tried serializing a QuerySet or Dict using a datetime.date following ways:

Method number 1:

 json.dumps(MyModel.objects.values()) 

Causes an error:

Exception value: [{'date': datetime.date (2012, 5, 26), "time": datetime.time (0, 42, 27)}] is not serializable JSON

Method number 2:

 json.dumps(MyModel.objects.values(), cls=DjangoJSONEncoder) 

An error also occurs:

Exception value: [{'date': datetime.date (2012, 5, 26), "time": datetime.time (0, 42, 27)}] is not serializable JSON

Way number 3:

 json.dumps(MyModel.objects.all(), cls=DjangoJSONEncoder) 

Exception value: [<MyModel: MyModel object]] is not serializable JSON

Method number 4:

 serializers.serialize('json', MyModel.objects.all()) 

Causes an error:

Exception value: object 'str' does not have attribute '_meta'

How to serialize an object with a datetime field in JSON in Django?

+4
source share
2 answers

Your problem is not related to dates. It is just that the requests are not directly serializable, even with the DjangoJSONEncoder class and even using values() . You will get exactly the same result with a model without date and time fields.

The way you should do serialization in Django is to use serializers :

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

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

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

If you want to just load the dictionary into JSON, just use json.dumps. It can be easily done to serialize objects by passing to a custom serialization class - there, which is included in Django, which already deals with dates:

 from django.core.serializers.json import DjangoJSONEncoder json.dumps(mydict, cls=DjangoJSONEncoder) 
+3
source

Source: https://habr.com/ru/post/1414501/


All Articles