Rakmo
Rakmo

Reputation: 1982

Correct way to format input and output of TimeField in Django Rest Famework?

models.py

class DemoA(models.Model):
    my_time = models.TimeField()

serializers.py

class DemoASerializer(serializer.ModelSerializer):
    class Meta:
        model = DemoA
        fields = ('my_time', )

By default, for my_time field, it gives the format as 10:30:00, (%H:%M:%S). What is want is the serialized format as 10:30, (%H:%M).

Is there any default way to specify format for such cases, like specifying extra_kwargs in serializer Meta?

Upvotes: 4

Views: 1279

Answers (2)

Stargazer
Stargazer

Reputation: 1530

Setting the format on the serializer works, but it can be antipattern on scale, since you will need to add it to all your serializers across your entire application. DRF allows you to set it on your settings as the default format for your application. You show set it, and override the format on serializer only when needed.

REST_FRAMEWORK = {
   ... # your other stuff
   'TIME_INPUT_FORMATS': ('%H:%M', )
}

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can specify how the field should format the data by specifying a TimeField [drf-doc] (this is not the TimeField [Django-doc] of the Django model):

class DemoASerializer(serializers.ModelSerializer):

    my_time = serializers.TimeField(format='%H:%M')

    class Meta:
        model = DemoA
        fields = ('my_time', )

or with extra_kwargs [drf-doc]:

class DemoASerializer(serializers.ModelSerializer):

    class Meta:
        model = DemoA
        fields = ('my_time', )
        extra_kwargs = {'my_time': {'format': '%H:%M'}}

Upvotes: 6

Related Questions