0
0
DjangoHow-ToBeginner · 3 min read

How to Use __startswith in Django Query Filters

In Django, use the __startswith lookup in query filters to find records where a field's value begins with a specific string. For example, Model.objects.filter(field__startswith='abc') returns all objects whose field starts with 'abc'. This is case-sensitive by default.
📐

Syntax

The __startswith lookup is used in Django ORM queries to filter records where a string field starts with a given substring.

It follows this pattern:

  • Model.objects.filter(field__startswith='value')

Here, field is the model's string field, and 'value' is the starting substring to match.

This lookup is case-sensitive by default. To perform a case-insensitive search, use __istartswith.

python
Model.objects.filter(field__startswith='value')
💻

Example

This example shows how to filter a list of books whose titles start with 'Django'. It demonstrates the use of __startswith in a Django queryset.

python
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)

# Assume we have these books in the database:
# Book(title='Django for Beginners')
# Book(title='Django Unleashed')
# Book(title='Python Crash Course')

# Query to get books starting with 'Django'
django_books = Book.objects.filter(title__startswith='Django')

for book in django_books:
    print(book.title)
Output
Django for Beginners Django Unleashed
⚠️

Common Pitfalls

Common mistakes when using __startswith include:

  • Expecting case-insensitive matching without using __istartswith.
  • Using it on non-string fields, which will cause errors.
  • Forgetting that it matches only the start of the string, not anywhere inside.

Example of wrong and right usage:

python
# Wrong: case-insensitive search with __startswith (will miss matches)
Book.objects.filter(title__startswith='django')  # No results if titles start with 'Django'

# Right: use __istartswith for case-insensitive search
Book.objects.filter(title__istartswith='django')
📊

Quick Reference

LookupDescriptionCase Sensitivity
field__startswith='value'Matches records where field starts with 'value'Case-sensitive
field__istartswith='value'Matches records where field starts with 'value' ignoring caseCase-insensitive

Key Takeaways

Use __startswith in Django filters to find records starting with a specific string.
It is case-sensitive by default; use __istartswith for case-insensitive matching.
Only use __startswith on string fields to avoid errors.
Remember it matches only the beginning of the string, not substrings elsewhere.
Test queries in Django shell to verify expected results.