簡體   English   中英

使用AND的列表上的Django過濾器QuerySet

[英]Django Filter QuerySet on List Using AND

我正在嘗試將Django的.filter()方法與相關子對象的列表一起使用,以返回包含所有子記錄的父對象集。 請參見下面的示例。

用戶是父對象,顏色是與用戶直接相關的子對象

  • User1具有顏色[red, blue]
  • User2具有顏色[black, purple, green, blue]
  • User3具有顏色[red, blue, green]
  • User4具有顏色[red, blue, green, white]

users = users.filter(user_colors__color__in=colors)

colors是POST設置的列表。 例如[red, blue, green]

當前,用戶包含具有[red, blue, green]任何一個的一組用戶。 對於上面的示例集,我目前正在使用上面的代碼獲取User1User2User3User4 即它正在使用OR搜索。 我只想返回具有所有指定顏色的用戶。 即使用AND搜索。 對於上面的示例,我只想獲取User3User4

什么是僅獲取具有所有請求的子記錄(顏色)的父記錄(用戶)集的最佳方法? 有沒有可以輕松做到這一點的Django方法? 還是我需要一個循環來過濾每種顏色?

謝謝!

假設您從其他地方獲得了顏色列表,我猜是這樣:

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對象進行過濾。

一個簡單的for循環就足夠了:

# list of color instances
colors = [red, green, blue]

for x in colors:
    users = users.filter(user_colors__color=x) 

連續過濾器將作為AND

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM