DRF在GET响应与POST响应中以不同方式序列化日期时间

时间:2015-09-09 18:40:45

标签: python django datetime django-rest-framework

class Event(models.Model):
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

class EventSerializer(serializers.ModelSerializer):
    bar = serializers.SerializerMethodField()

    class Meta:
        model = Event
        fields = ('id', 'start_date', 'end_date')

一切都很好,花花公子:

GET .../api/v1/Event/
{
"count":23,
"next":null,
"previous":null,
"results":[{
   "databaseId":101488,
   "start_date":"2013-11-01T09:46:25",
   "end_date":"2013-11-02T09:46:25"
},...
]}

现在,当我创建一个新事件时:

POST /api/v1/Event/
{
   "start_date":"2013-11-03T09:46:25",
   "end_date":"2013-11-04T09:46:25"
}

在JSON响应中,我得到:

{
   "databaseId":101489,
   "start_date":"2013-11-03T09:46:25.250000",
   "end_date":"2013-11-04T09:46:25.750000"
}

所以我得到了更精确的格式。我想恢复完全相同的格式,因此客户端开发人员不必编写不同的解析器代码。

我正在使用Python 2.7,DRF 3.1.3,Django 1.4.21(我知道它已经过时了,但它是一个很大的代码库,有一天我们会迁移)。

1 个答案:

答案 0 :(得分:0)

到目前为止,我无法找出导致此问题的原因,但明确强制执行格式字符串有助于:

////Arrays/////

   /////song 197 -  artist jackson////

"197"         => array(

"title"    => "a song with a id - 197",


"chords"    => " ....",

"artist"    => "jackson ",                        

"tags"    => "unknown "

),


   /////song 210 - with same artist jackson////


"210"         => array(

"title"    => "another song with different id - 210 in other table",


"chords"    => " ....",

"artist"    => "jackson",                        

"tags"    => "unknown "

),