Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset filter GT, LT, GTE, LTE returns full object list

I'm trying to filter objects in my database using .filter(field__lte = parameter) however it just returns ALL objects and does not filter any out. I have even set the parameter to well above any value that is stored in the database and all objects are still returned.

>> all_objects = Ranked.objects.all()
>> filtered = all_objects.filter(score__lte = 100) #The max possible score is 100
>> len(filtered)
87 #Every object in the db

The field in the database that I am querying against is an IntegerField.

Am I doing something wrong here? Thanks for your help.

like image 895
apardes Avatar asked Jun 13 '14 17:06

apardes


People also ask

What does QuerySet filter return?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What does Django filter return?

Django provides a filter() method which returns a subset of data. It accepts field names as keyword arguments and returns a QuerySet object. As database has only one record where name is 'tom' , the QuerySet object contains only a single record.

What is __ GT in Django?

Field Lookups - gt (greater than, or equal to) The gte lookup is used to get records that are larger than, or equal to, a specified value. For a greater than, but not or equal to, search, use the gt lookup.


2 Answers

As you said max possible score is 100 so it will always return all objects because lte means return all objects whose score is either less than or equal to 100. You might need lt lookup which means just return those objects whose score is less than 100:

filtered = all_objects.filter(score__lt=100)
like image 73
Aamir Rind Avatar answered Sep 18 '22 09:09

Aamir Rind


You are saying that The max possible score is 100. By using score__lte=100, you are filtering all objects with score less than or equal to 100 - which is every object in the table by your own definition.

like image 39
alecxe Avatar answered Sep 18 '22 09:09

alecxe