Python Django QuerySet Filter LIKE Operator Example

Published On: 25/08/2022 | Category: Django


Hi Dev,

In this article we will cover on how to implement python django queryset filter like operator example. if you have question about python django filter like example then I will give simple example with solution. step by step explain django filter contains string. We will use django orm filter like.

So, The example related to contains field lookup. To confirm whether the contains option is equivalent to the LIKE operator, we will run the following given code.

So, If your mind raised one question what is difference between contains and icontains like how to both work search like queryset in django orm. so 'contains': 'LIKE BINARY %s',and 'icontains': 'LIKE %s'.the binary is the exact case and the 'i' in 'icontains' means that case is ignored,

let's see bellow example here you will learn python django queryset filter like example.

Django Admin Interface:



Example

In this example we will use the same Employee model. to get the Get employees firstname with __contains field lookup get the object.

views.py
from django.http import HttpResponse
from core.models import Employee

def index(request):
    queryset = Employee.objects.filter(firstname__contains='Bha').values()
    print(queryset)

    return HttpResponse(queryset)
Output
[
    {
        'id': 1, 
        'firstname': 'Bhavesh', 
        'lastname': 'Sonagra'
    }
]
Example

In this second example we will use the same Employee model. to get the Get employees firstname with __contains field lookup get the object.

views.py
from django.http import HttpResponse
from core.models import Employee

def index(request):
    queryset = Employee.objects.filter(firstname__icontains='bha').values()
    print(queryset)

    return HttpResponse(queryset)
Output
[
    {
        'id': 1, 
        'firstname': 'Bhavesh', 
        'lastname': 'Sonagra'
    }
]

I Hope It will help you....