Fix Python – How to do a less than or equal to filter in Django queryset?

Question

Asked By – Finglish

I am attempting to filter users by a custom field in each users profile called profile. This field is called level and is an integer between 0-3.

If I filter using equals, I get a list of users with the chosen level as expected:

user_list = User.objects.filter(userprofile__level = 0)

When I try to filter using less than:

user_list = User.objects.filter(userprofile__level < 3)

I get the error:

global name ‘userprofile__level’ is not defined

Is there a way to filter by < or >, or am I barking up the wrong tree.

Now we will see solution for issue: How to do a less than or equal to filter in Django queryset?


Answer

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

This question is answered By – lprsd

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0