Python Django Filter less than Example

Published On: 06/09/2022 | Category: Django


Hi Dev,

Now, let's see article of django filter less than example. Here you will learn python django filter less than example. you can understand a concept of django filter less than equal to example. This post will give you simple example of django less than filter. Follow bellow tutorial step of filter less than django.

So, The example related to lt and lte field lookup. Let’s understand how to use the “less than” and less than or equal to” operator with the help of an example. we will run the following given code.

let's see bellow example here you will learn python django filter less than example.

Django Admin Interface:



Example: 1

In this example how to use the “less than” operator with the help of an example. we are going to select all the database objects whose age is less than 22. The code for the example is as follows.

views.py
from django.http import HttpResponse
from base.models import Student

def index(request):
    queryset = Student.objects.filter(age__lt=22).values()
    print(queryset)

    return HttpResponse(queryset)
Output
[
    {
        'id': 2, 
        'name': 'Nikhil', 
        'age': 20
    },
    {
        'id': 5, 
        'name': 'Vishal', 
        'age': 19
    }
]
Example: 2

In this second example So, we are using the filter() method and in the method, we have passed “age__lte=22” as an argument.select all the objects from the Student model whose age is greater than or equal to 22

views.py
from django.http import HttpResponse
from base.models import Student

def index(request):
    queryset = Student.objects.filter(age__lte=22).values()
    print(queryset)

    return HttpResponse(queryset)
Output
[
    {
        'id': 2, 
        'name': 'Nikhil', 
        'age': 20
    }, 
    {
        'id': 3, 
        'name': 'Keval', 
        'age': 22
    }, 
    {
        'id': 5, 
        'name': 'Vishal', 
        'age': 19
    }
]

I Hope It will help you....