python Django 自定义查询集过滤器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/672182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django Custom Queryset filters
提问by interstar
Is there, in Django, a standard way to write complex, custom filters for QuerySets?
在 Django 中,是否有一种标准方法可以为 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.
但这会失去可链接性和 QuerySets 提供的任何其他功能。
回答by Carl Meyer
The recommendation to start using manager methods is a good one, but to answer your question more directly: yes, use Q objects. For example:
开始使用管理器方法的建议是一个很好的建议,但要更直接地回答您的问题:是的,使用Q objects。例如:
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).
Q 对象可以与 | 结合使用 (OR)、& (AND) 和 ~ (NOT)。