有问题...

我使用DjangoSQLitejqueryAJAX

问题是,当我从数据库中获取日期和时间时,它看起来很奇怪。

有什么办法可以正常显示为dd/mm/yyyy HH:MM吗?

模型

class QueryHistory(models.Model) :
 userID = models.CharField(max_length=100)
 date = models.DateTimeField(auto_now_add=True, blank=True)


View.py

queries_list = serializers.serialize(
             'json',
             (QueryHistory.objects.filter(
                 userID = request.session['user_id']
               ).order_by('-id')[:5])
           )
return HttpResponse(json.dumps(queries_list), content_type="application/json")


js文件

success : function(response) {
 var queries_list = jQuery.parseJSON(response);
 console.log(response);
}



结果:2016-09-21T06:43:26.693Z

应该是:21/09/2016 06:43

最佳答案

这并不奇怪,它是ISO 8601,更改它不是一个好主意。但是您可以通过定义自己的编码器:

import json
from datetime import dateteime

from django.forms.models import model_to_dict
from django.core.serializers.json import DjangoJSONEncoder

class MyEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, date):
            return obj.strftime('%d.%m.%Y')
        return super(MyEncoder, self).default(obj)


json.dumps([model_to_dict(o) for o in QueryHistory.objects.all()], cls=MyEncoder)


或通过自己的序列化器:

import json
from datetime import dateteime

from django.core.serializers.python import Serializer

class MySerializer(Serializer):
    def handle_field(self, obj, field):
        value = field.value_from_object(obj)
        if isinstance(value, date):
            self._current['date'] = value.strftime('%d.%m.%Y')
        else:
            super(MySerializer, self).handle_field(obj, field)


serializer = MySerializer()
queries_list = serializer.serialize(QueryHistory.objects.all())
json.dumps(queries_list)

10-08 02:42