Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Filter objects by integer between two values

Tags:

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?

like image 338
Daniel Avatar asked Oct 13 '15 14:10

Daniel


People also ask

How can I filter a Django query with a list of values?

The sql query will be like SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9] which is not true. You have to use in operator for this so you query will be like SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9) for that Django provide __in operator.

How do you use get and filter together in Django?

This exception is also an attribute of the model class. Returns a new QuerySet containing objects that match the given lookup parameters. Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters. Show activity on this post.

Can you filter by property Django?

Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.

What does .values do in Django?

The values_list() method allows you to return only the columns that you specify.


2 Answers

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

like image 166
Geo Jacob Avatar answered Sep 26 '22 12:09

Geo Jacob


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

like image 31
garnertb Avatar answered Sep 22 '22 12:09

garnertb