PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

[FIXED] How to provide choices to django rest framework DecimalField serializer?

 August 11, 2022     choicefield, decimal, django, django-rest-framework, python     No comments   

Issue

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?


Solution

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%')


Answered By - Mohamed Abd El-hameed
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing