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

PythonDjangoDjango Queryset

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFinglishView Question on Stackoverflow
Solution 1 - PythonlprsdView Answer on Stackoverflow