Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework format decimal field to 2 decimal places (for output)

I use Django and DRF,I have many decimal fields in models, like

amount = models.DecimalField(max_digits=16, decimal_places=4)

I want format output Two decimal places ,in every serializers field can do this

amount = serializers.DecimalField(max_digits=16, decimal_places=2)

There's an easyer way?

like image 502
Jeff Zzz Avatar asked Oct 28 '25 12:10

Jeff Zzz


1 Answers

In DRF there is a way to override only options but not the entire field:

class MySerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = ('amount',)
        extra_kwargs = {
            'amount': {'max_digits': 16, 'decimal_places': 2}
        }

Or if you have many same decimal fields you should use your own custom DecimalField with predefined common options.

like image 100
Andrey Bogoyavlensky Avatar answered Oct 30 '25 03:10

Andrey Bogoyavlensky