Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 949
Rakmo Avatar asked Jan 26 '23 06:01

Rakmo


2 Answers

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'}}
like image 195
Willem Van Onsem Avatar answered Jan 29 '23 10:01

Willem Van Onsem


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', )
}
like image 39
Stargazer Avatar answered Jan 29 '23 10:01

Stargazer