Daniel
Daniel

Reputation: 1575

Django: Filter objects by integer between two values

I'm struggling with a Django filtering problem I couldn't solve so far. I have a database with from/to integers, and I need a Django Filter that returns any objects where a given integer is within that 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, lets say, 170. I need all objects where 170 is between i_begin_int and i_end_int. In the example table, that would be objects with id 1 and 2.

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

Upvotes: 23

Views: 34121

Answers (2)

Geo Jacob
Geo Jacob

Reputation: 6009

Try this;

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

where; gte = greater than equal to lte = less than equal to

Upvotes: 35

garnertb
garnertb

Reputation: 9584

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

Filter where i_begin_int is less than 170 AND the i_end_int value is greater than 170.

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

Upvotes: 3

Related Questions