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 IntegerField
s. 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 ForeignKey
s instead of IntegerField
s: ForeignKey
s will guarantee referential integrity and make it more convenient to work with the Django ORM.