'Django queryset on floating point range
I came through a problem which I never happened to face before in Django queryset. I have more then 1,00,000 of floating point datatype (records) along with foreign key field in one data model class. What I am trying to do is query on these records with following procedure.
- User will enter value (v) e.g 1248.597290039063(float point) and filter like preicison (f) (how many digits to accept after decimal). If precision is 5 then I will take only 5 numbers after decimal point, e.g (1248.59729). I will get these request from html template and do rest operation on the view.
- Default parameter ( p) = 0,000005
- new value (nv) = p* v
- Highest range (HR) = v + nv
- Lowest range (LR) = v- nv
- Now, HR and LR is the search space where query should be done.
So, please only focus on querying on such range after decimal point (fixed) ?
If question is not clear enough please do comment. I will again try my best.
Guide me
Solution 1:[1]
If you have the high and low ends of your range already computed, then you can use a simple range query in Django:
objects = my_model.objects.filter(field__gte=LR, field__lte=HR)
or, somewhat shorter:
objects = my_model.objects.filter(field__range=(LR, HR))
(You'll have to replace 'my_model' and 'field' with your actual model and field names, of course)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ian Clelland |