Django Custom Queryset filters

荒凉一梦 提交于 2019-12-04 11:28:35

问题


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.


回答1:


I think you may need custom managers.




回答2:


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



来源:https://stackoverflow.com/questions/672182/django-custom-queryset-filters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!