代码之家  ›  专栏  ›  技术社区  ›  Csaba Toth

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

  •  0
  • Csaba Toth  · 技术社区  · 9 年前
    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 回复  |  直到 9 年前
        1
  •  1
  •   Csaba Toth    9 年前

    到目前为止,我还不知道是什么原因导致了这种情况,但显式强制执行格式字符串有助于:

    start_date=serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')