SoFunction
Updated on 2025-03-02

Basic operations of using filter method in Django for data query

Basic usage

1. Equal to (=)

results = (title='Example')

2. Not equal to (exclude)

results = (title='Example') 

3. Greater than (__gt) / Greater than or equal to (__gte)

results = (price__gt=10)
results = (price__gte=10)

4. Less than (__lt) / Less than or equal to (__lte)

results = (price__lt=10)
results = (price__lte=10)

5. Include (__contains) / Not including (exclude + __contains)

results = (title__contains='Example')
results = (title__contains='Example')

6. Start at (__startswith) / End at (__endswith)

results = (title__startswith='Ex')
results = (title__endswith='ple')

7. Regular expression matching (__regex)

results = (title__regex=r'^Ex.*')

8. Whether it is empty (__isnull)

results = (price__isnull=True)
results = (price__isnull=False)

Combination query

1. AND Conditions

results = (title='Example', price__gt=10)

2. OR condition (using Q object)

from  import Q

results = (Q(title='Example') | Q(price__gt=10))

IN query

1. __in query

results = (id__in=[1, 2, 3])

Date query

1. Date field (__date, __year, __month, __day, __week_day)

results = (created_at__date='2024-05-21')
results = (created_at__year=2024)
results = (created_at__year=2024, created_at__month=5)
results = (created_at__year=2024, created_at__month=5, created_at__day=21)

Foreign Key Field Query

1. Cross-table query

results = (user__email='example@') 

Sample code

# Import necessary modules and classesfrom  import models

# Create a model classclass MyModel():
    title = (max_length=100)
    price = (max_digits=10, decimal_places=2)
    created_at = ()

# Use filter method to query dataresults = (title='Example', price__gt=10)

# Print the resultsfor result in results:
    print(result)

This is the introduction to this article about the basic operations of using the filter method in Django for data query. For more related Django filter data query content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!