我的模型:
Item:
name
desc
Type:
name
Value:
text
type.ForeignKey(Type)
item = ForeignKey(Item)
我有一个来自表 Type 的初始类型列表,假设 t = [4,5,6]。现在我必须得到一个类型为 t 的项目列表。例如:
值的数据列表:
type | item
4 1
5 1
6 1
4 2
5 2
4 3
所以,如果 t = [4,5,6],我需要的结果是 items = [<object: 1>]
更新:
t = [4,5] items = [<object: 1>, <object: 2>]
t = [4] items = [<object: 1>, <object: 2>, <object: 3>]
感谢您的帮助!!!
最佳答案
不太确定这是最好的解决方案,但它有效
from itertools import groupby
values = Value.objects.filter(type_id__in=t).values_list('type_id', 'item_id')
values = sorted(values, key=lambda x: x[1])
items = []
for key, group in groupby(values, lambda x: x[1]):
types = [x[0] for x in group]
if set(t).issubset(set(types)):
items.append(key)
items
将包含 id,而不是对象,但我认为这不是问题。
关于python - Django - 使用过滤器获取项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5908388/