gpt4 book ai didi

python - 排除 vs 过滤器,当使用 Q 对象时

转载 作者:太空宇宙 更新时间:2023-11-04 04:47:15 29 4
gpt4 key购买 nike

无法理解这是怎么可能的:

A = object_list.filter( Q(sales__sale_starts__lte=today) & Q(sales__sale_ends__gte=today) )
# query inside filter catches 2 objects

B = object_list.exclude( Q(sales__sale_starts__lte=today) & Q(sales__sale_ends__gte=today) )
# query inside exclude catches 3 objects,
# though it is the same as previous

# in other words: object_list contains 20 objects,
# A - 2 objects, and B - 17 objects

使用 Q 对象时,filter()exclude() 的工作方式有什么不同吗?谢谢。

我希望 B 如下所示:

B = object_list.difference(A)
# B contains 18 objects

最佳答案

行为应该是一样的。如果您查看 .exclude().filter() 源代码,它们的作用相同:

def exclude(self, *args, **kwargs):
"""
Returns a new QuerySet instance with NOT (args) ANDed to the existing
set.
"""
return self._filter_or_exclude(True, *args, **kwargs)

def filter(self, *args, **kwargs):
"""
Returns a new QuerySet instance with the args ANDed to the existing
set.
"""
return self._filter_or_exclude(False, *args, **kwargs)

_filter_or_exclude() 只是用 ~ 否定你的 Q 过滤器

def _filter_or_exclude(self, negate, *args, **kwargs):
if args or kwargs:
assert self.query.can_filter(), \
"Cannot filter a query once a slice has been taken."

clone = self._clone()
if negate:
clone.query.add_q(~Q(*args, **kwargs))
else:
clone.query.add_q(Q(*args, **kwargs))
return clone

关于python - 排除 vs 过滤器,当使用 Q 对象时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49246582/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com