I have an object with a DecimalField value of 5.60. I'm making a query:
Mdl.objects.get(speed__iexact="5.60")
This will return the correct result. But this will not:
Mdl.objects.get(speed__iexact="5.6")
Is there a way to automatically reconcile this inconsistency? The filter value is user provided, so I want to be sure that a user typing 5.6 can find the object.
iexact
does an case-insensitive equality check, which is normally used for strings. For decimals with two decimal places, the Django database backend will probably store "5.60" as string for a DecimalField
, so iexact-comparison with that will work because the strings are equal. But as you want to compare numbers, not strings, you should just use the normal equality operator.
from decimal import Decimal
Mdl.objects.get(speed=Decimal("5.6"))
Don't use strings, instead use the Python-builtin Decimal type. When retrieving model instances with Django, you will get instances of that type anyway, so you should also assign this type in order to be consistent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With