Django decimal field query

I have an object with a DecimalField value of 5.60. I am making a request:

Mdl.objects.get(speed__iexact="5.60") 

This will return the correct result. But it will not be:

 Mdl.objects.get(speed__iexact="5.6") 

Is there a way to automatically reconcile this inconsistency? The filter value is provided to the user, so I want to be sure that the user who typed 5.6 can find the object.

+4
source share
1 answer

iexact performs a case insensitive equality check that is commonly used for strings. For decimal places with two decimal places, the backend of the Django database will probably keep "5.60" as a string for DecimalField , so an iexact comparison with this will work because the strings are equal. But since you want to compare numbers, not strings, you should just use the regular equality operator.

 from decimal import Decimal Mdl.objects.get(speed=Decimal("5.6")) 

Do not use strings, instead use the Decimal type created by Python. When retrieving model instances using Django, you will still get instances of this type, so you must also assign this type to be consistent.

+8
source

Source: https://habr.com/ru/post/1334253/


All Articles