我正在尝试使用Django的.filter()方法和一系列相关的子对象,以返回包含所有子记录的父对象集。请参阅下面的示例。
用户是父对象,颜色是与用户直接相关的子对象
- User1的颜色为
[red, blue]
- 用户2具有颜色
[black, purple, green, blue]
- User3具有颜色
[red, blue, green]
- 用户4具有颜色
[red, blue, green, white]
users = users.filter(user_colors__color__in=colors)
colors是POST设置的列表。例如[red, blue, green]
目前,users包含一组具有[red, blue, green]
的用户。对于上面的示例集,我目前正在使用上面的代码获得User1
、User2
、User3
和User4
。即使用OR搜索。我只想返回具有所有指定颜色的用户。即使用AND搜索。对于上面的例子,我只想得到User3
和User4
。
只获取具有所有请求的子记录(颜色)的父记录(用户)集的最佳方法是什么?有没有一个Django方法可以轻松做到这一点?或者我需要一个对每种颜色进行过滤的循环吗?
谢谢!
一个简单的for循环就足够了:
# list of color instances
colors = [red, green, blue]
for x in colors:
users = users.filter(user_colors__color=x)
连续滤波器将作为AND 操作
假设您从其他地方获得颜色列表,我猜是这样的:
from django.db.models import Q
# list of color instances
colors = [red, green, blue]
# create a list Q filters dynamically
filter_by_this = [Q(user_colors__color=color) for color in colors]
# filter using the filter as a list of arguments
users = users.filter(*filter_by_this)
这还没有经过测试,但我认为应该是这样的。
在任何情况下,您都应该阅读有关使用Q对象进行过滤的内容。