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?
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.
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.
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.
The values_list() method allows you to return only the columns that you specify.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With