Home > other >  ValidationError "value must be a decimal number"
ValidationError "value must be a decimal number"

Time:10-17

I have a model

class FunderProgramMember(models.Model):
buyer = models.IntegerField()
supplier = models.IntegerField()
discount_rate = models.DecimalField(max_digits=3, decimal_places=2)

In my serializer I am trying to get the discount field:

discount_rate = FunderProgramMember.objects.values('discount_rate').get(supplier=item.invoice.supplier_id, buyer=item.invoice.buyer)

Even if I replace my filter "get(supplier=item.invoice.supplier_id, buyer=item.invoice.buyer)" with pk=2 I still receive the following validation error: ["“{'discount_rate': Decimal('0.25')}” value must be a decimal number."]

It appears to get a decimal value. How do I fix this error?

CodePudding user response:

If you work with the .supplier_id and buyer_id, then the query will succeed, since the fields are IntegerFields. Likely the rest of the view rases the exception.

This is because your discount_rate is not a Decimal object, but a dictionary containing that item. You can work with .values_list(…, flat=True) [Django-doc] to retrieve a scalar result:

discount_rate = FunderProgramMember.objects.values_list('discount_rate', flat=True).get(
    supplier=item.invoice.supplier_id, buyer=item.invoice.buyer
)

I would further advise to work with ForeignKeys instead of IntegerFields: ForeignKeys will guarantee referential integrity and make it more convenient to work with the Django ORM.

  • Related