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.
3
1 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.
5
Wow, that was fast :). This works great for less than or equal, but how about just less than? (userprofile__level__lt=3) doesn’t seem to work
–It does; but in any case, you can also do exclude(__gte) instead of filter(__lt).
– lprsdAnd do NOT forget that there are two
__
underlines– andilabsIm getting this error–> {FieldError}Unsupported lookup ‘level’ for AutoField or join on the field not permitted.
question, what does =0 mean here? false? true?
@BéresBotond Although the docs look great – the structuring and layout is so poor that without a direct link, they are all but useless
@BéresBotond Unfortunately that link is now dead 🙁
Working link for doc: docs.djangoproject.com/en/1.11/ref/models/querysets/#gt