Apon
Apon

Reputation: 152

How to provide choices to django rest framework DecimalField serializer?

Django==2.2.6

djangorestframework==3.10.3

Models.py

VAT_CHOICES = [(Decimal('0.00'), '0%'), (Decimal('6.00'), '6%'), (Decimal('12.00'), '12%'), (Decimal('25.00'), '25%')]
class Service(models.Model):
    vat = models.DecimalField(verbose_name=_('vat'), decimal_places=2, max_digits=10, choices=VAT_CHOICES)

serializers.py

class ServiceSerializer(serializers.ModelSerializer):
    vat = serializers.DecimalField(decimal_places=2, max_digits=10, coerce_to_string=True)

If I do this then the value of vat in response is in srting as expected but the choices validation does not implied then.

Now I can create a service with vat="5.00" which should not be possible because there is a choice list in the model.

How can I have the string representation of the decimal field vat but keep the choices validation?

Upvotes: 2

Views: 564

Answers (1)

Mohamed Abd El-hameed
Mohamed Abd El-hameed

Reputation: 420

I think this will help you

from rest_framework import serializers
from django.core.validators import DecimalValidator

class ServiceSerializer(serializers.ModelSerializer):
    vat = serializers.ChoiceField(choices=[(Decimal('0.00'), '0%'), (Decimal('6.00'), '6%'), (Decimal('12.00'), '12%'),
                                           (Decimal('25.00'), '25%')], validators=[DecimalValidator(max_digits=10, decimal_places=2)])

    def to_representation(self, instance):
        data = super(ServiceSerializer, self).to_representation(instance)
        data.update(vat=str(instance.vat))
        return data

Ii think there is no need for validating max_digits and decimal_places as choices will not accept other values except

choices=[(Decimal('0.00'), '0%'), (Decimal('6.00'), '6%'), (Decimal('12.00'), '12%'),('25.00'), '25%')

Upvotes: 1

Related Questions