简体   繁体   中英

Django Custom Queryset filters

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.

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).

I think you may need custom managers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM