Django Custom Queryset filters
Asked Answered
S

2

10

Is there, in Django, a standard way to write complex, custom filters for QuerySets?

Just as I can write

MyClass.objects.all().filter(field=val)

I'd like to do something like this :

MyClass.objects.all().filter(customFilter)

I could use a generator expression

(x for x in MyClass.objects.all() if customFilter(x))

but that would lose the chainability and whatever other functions the QuerySets provide.

Speculator answered 23/3, 2009 at 3:53 Comment(0)
E
10

I think you may need custom managers.

Ecosphere answered 23/3, 2009 at 3:53 Comment(2)
I guess I do need this. But it looks awfully complicated compared to just being able to pass a filter function in on the fly.Speculator
It's not very complicated, and it's a good practice to make custom managers, especially if you plan on caching stuff from db etc.Ecosphere
B
16

The recommendation to start using manager methods is a good one, but to answer your question more directly: yes, use Q objects. For example:

from django.db.models import Q

complexQuery = Q(name__startswith='Xa') | ~Q(birthdate__year=2000)

MyModel.objects.filter(complexQuery)

Q objects can be combined with | (OR), & (AND), and ~ (NOT).

Bernadinebernadotte answered 23/3, 2009 at 3:53 Comment(0)
E
10

I think you may need custom managers.

Ecosphere answered 23/3, 2009 at 3:53 Comment(2)
I guess I do need this. But it looks awfully complicated compared to just being able to pass a filter function in on the fly.Speculator
It's not very complicated, and it's a good practice to make custom managers, especially if you plan on caching stuff from db etc.Ecosphere

© 2022 - 2024 — McMap. All rights reserved.