Django .filter 在同一个选项上有多种可能性 [英] Django .filter on same option with multiple possibilities

查看:18
本文介绍了Django .filter 在同一个选项上有多种可能性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象模型.我还有一个用于过滤结果的选项列表.我不确定是否有一种简单的方法来过滤模型中的对象,以便返回与过滤器列表中的任何项目匹配的任何对象.例如:

I have a model of objects. I also have a list of options to filter results with. I'm not sure if there is an easy way to filter the objects in the model such that any object that matches any of the items in the filter list is returned. For example:

# returns all users with name starting with 'P'
usersWithPName = User.objects.filter(name__startswith = 'P')
# 3 letters to filter User model with
filterList = ['P', 'T', 'R'] 
# ideally would return all users with name starting with either 'P', 'T', or 'R'
usersWithPTRName = User.objects.filter(name__startswith = filterList) 

有没有办法过滤(在这种情况下)用户模型,以便返回与 filterList 中的任何一项匹配的任何对象?

Is there any way to filter (in this case) the User model such that any object matching any one of the items in the filterList is returned?

推荐答案

这可以通过 Q 个对象

from django.db.models import Q
usersWithPTRName = User.objects.filter(Q(name__startswith='P') |
                                       Q(name__startswith='T') |
                                       Q(name__startswith='R')) 

您也可以在运行时构建 Q 过滤器:

Also you can build Q filters at runtime:

filterList = ['P', 'T', 'R']
query = Q()
for letter in filterList:
    query = query | Q(name__startswith=letter)
usersWithPTRName = User.objects.filter(query)

这篇关于Django .filter 在同一个选项上有多种可能性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆