Ed.
Ed.

Reputation: 4597

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.

Upvotes: 4

Views: 6140

Answers (1)

AndiDog
AndiDog

Reputation: 70238

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.

Upvotes: 9

Related Questions