serialize datetime to json in Django

前端 未结 3 1158
渐次进展
渐次进展 2020-11-30 05:11

Hi how do I get DateTimeField from Mysql database in Django in json format? I got an error when I executed the code \'Date.time cannot be serialized in json\'(data holds a l

相关标签:
3条回答
  • 2020-11-30 05:20

    Whenever you see an error message of the form ... object has no attribute '_meta' that is a clear-cut sign that a method was expecting a queryset but got something else. In this particular situation, serializers.serialize must have a queryset for its second argument. You can't use a list, dictionary, etc., and definitely not a string.

    Where is data being set. Check to make sure it's being assigned a true queryset. You might also want to post more of your code, if you're still having issues. It's difficult to diagnose the problem much more, out of context.

    0 讨论(0)
  • 2020-11-30 05:21

    DjangoJSONEncoder solved my problem.

    import json
    from django.core.serializers.json import DjangoJSONEncoder
    data = json.dumps(data, cls=DjangoJSONEncoder)
    
    0 讨论(0)
  • 2020-11-30 05:22

    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.

    0 讨论(0)
提交回复
热议问题