Csaba Toth
Csaba Toth

Reputation: 10699

DRF serializes datetime differently in the GET response vs POST response

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')

It works all fine and dandy:

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"
},...
]}

Now when I create a new event:

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

In the JSON response I get:

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

So I get back a more precise format. I'd like to get back exactly the same format, so the client developer won't have to write different parser codes.

I'm using Python 2.7, DRF 3.1.3, Django 1.4.21 (I know it's old but it's a large codebase, one day we'll migrate).

Upvotes: 0

Views: 287

Answers (1)

Csaba Toth
Csaba Toth

Reputation: 10699

So far I couldn't figure out what causes this, but explicitly enforcing format string helps:

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

Upvotes: 1

Related Questions