Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize datetime to JSON

Tags:

python

django

How do I get DateTimeField from MySQL in Django in JSON format? I got an error when I executed the code

Date.time cannot be serialized in json

(data holds a lot of values)

data = json.dumps(data)

But this was fixed by adding

ALL_data = serializers.serialize("json", data, ensure_ascii=False)

But now I get 'str' object has no attribute '_meta'.

like image 382
Rakesh Avatar asked Sep 06 '25 12:09

Rakesh


2 Answers

DjangoJSONEncoder solved my problem.

import json
from django.core.serializers.json import DjangoJSONEncoder
data = json.dumps(data, cls=DjangoJSONEncoder)
like image 158
Rakesh Avatar answered Sep 09 '25 22:09

Rakesh


Django's serializers are only meant to be used on query sets; you will have to find a different way to solve your problem, such as converting the datetime to something else first.

like image 40
Ignacio Vazquez-Abrams Avatar answered Sep 09 '25 22:09

Ignacio Vazquez-Abrams