Django select objects where field is in range [duplicate]

75
December 05, 2021, at 2:00 PM
This question already has answers here:
How to filter objects by price range in Django? (2 answers)
Closed 10 hours ago.

I have a django model called MyModel which has two fields:

a = models.IntegerField(...)
b = models.DateTimeField(...)

I would like to select all of the MyModels which have an a value between 0 and 10. For example:

results = [obj for obj in MyModel.objects.all() if 0 <= obj.a <= 10]

This works, but requires looping through every row in Python and is not efficient whatsoever.

As an extension to this, how would I perform a similar query for field b, selecting every object which has time within the last 15 minutes. This is how I would write the query in SQL:

SELECT * FROM appname_mymodel WHERE TIMESTAMPDIFF(MINUTE, b, CURRENT_TIMESTAMP) <= 15;

I would like a python + django way of writing this query, if possible.

Answer 1

Here is the API reference for 'Field Lookups' which are "how you specify the meat of an SQL WHERE clause".

For specifically the questions that I asked:

from datetime import datetime, timedelta
a_results = MyModel.objects.filter(a__range = (0, 10))
b_results = MyModel.objects.filter(b__gt = datetime.now() - timedelta(mintues = 15))
READ ALSO
PG Promise error when select then insert the data

PG Promise error when select then insert the data

i got error on my pg-promise like this:

72
Kotlin Coroutine: get List of (T) from Flow&lt;sealed class &lt;list of &lt;T&gt;&gt;&gt;

Kotlin Coroutine: get List of (T) from Flow<sealed class <list of <T>>>

I have the following function that return Flow<sealed class <list of < T > > > ,

33
Ajax Search Posts and Ajax Load more

Ajax Search Posts and Ajax Load more

I'm not that yet super familiar with AJAX but I'm learning

56
Is there a Postgrest API equivalent for MySQL?

Is there a Postgrest API equivalent for MySQL?

I earlier worked on postgres sql database and created some functions there which i called using postgrest api via postman

76