Django: filter objects by integer between two values

I am struggling with a Django filtering problem that I have not been able to solve so far. I have a database with / from integers, and I need a Django filter that returns any objects in which the given integer is within this range.

I have the following model (simplified):

class Dataset(models.Model): i_begin_int = models.BigIntegerField() i_end_int = models.BigIntegerField() 

So, for example, I have the following data:

 +----+-------------+-----------+ | id | i_begin_int | i_end_int | +----+-------------+-----------+ | 1 | 100 | 200 | +----+-------------+-----------+ | 2 | 150 | 300 | +----+-------------+-----------+ | 3 | 7000 | 7500 | +----+-------------+-----------+ 

So now I have an integer, let's say 170. I need all the objects where 170 is between i_begin_int and i_end_int . In the table of examples, these will be objects with identifiers 1 and 2.

Is there a Django filter that I could use for this?

+6
source share
2 answers

Try it;

 x = 170 Dataset.objects.filter(i_end_int__gte=x,i_begin_int__lte=x) 

Where; gte = more than lte = less than

+8
source
 Dataset.objects.filter(i_begin_int__lte=170, i_end_int__gte=170) 

A filter where i_begin_int is less than 170 and the value of i_end_int is greater than 170.

SQL equivalent: SELECT * FROM appname_dataset WHERE i_begin_int <= 170 AND i_end_int >= 170

+2
source

All Articles