Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query on decimal field

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.

like image 894
Ed. Avatar asked Jan 21 '23 19:01

Ed.


1 Answers

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.

like image 99
AndiDog Avatar answered Jan 28 '23 19:01

AndiDog