Advanced QuerySets (Django)

Advanced QuerySet techniques in Django include field lookups (__gte, __icontains, __in), spanning relationships in filters, values()/values_list() for dicts, and combining queries — going beyond simple equality filters.

Django

Field lookups extend filters past equality using a double-underscore suffix: filter(age__gte=18), filter(name__icontains='an'), filter(id__in=[1,2,3]), filter(created__year=2026). You can also span relationships: filter(author__name='Ana') joins to the related table automatically.

values() and values_list() return dicts or tuples instead of model instances, which is faster and handy for serialization or when you only need a couple of columns. distinct() removes duplicates, and exists() is the efficient way to check 'are there any?'.

For dynamic or complex conditions you combine Q objects with & and |, and for database-side computation you use F expressions and annotate(). These tools let you push work into the database rather than looping in Python.

Syntax

Model.objects.filter(field__lookup=value, rel__field=value)

Examples

Python

# field lookups and relationship spanning
Post.objects.filter(created__year=2026, author__name__icontains="an")

# values_list for a flat list of titles
titles = Post.objects.values_list("title", flat=True)

# efficient existence check
has_drafts = Post.objects.filter(published=False).exists()

Learn it in a lesson

See also

Back to the Dictionary