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
?
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'}}
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', )
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With