基于条件合并2查询集
问题描述:
背景: - 我试图合并来自同一模型的2个查询集。 就是这样。即每隔三个柜台他们应该合并。基于条件合并2查询集
queryset = get_foo(person) #First queryset
promoted_foo = get_promoted_foo() #Second queryset
for (counter,(s,p)) in enumerate(itertools.izip(queryset,promoted_foo)):
if counter%3==0:
queryset.insert(counter,promoted_foo.pop())
if promoted_foo:
queryset.extend(promoted_foo)
什么是最Python的方法来做到这一点? 我知道我可以在quersets上使用list(),然后合并它们。但是这消耗了大量的记忆。那么可以选择什么呢?
答
您可能会定义自己的生成器,从查询集中延迟加载项目。
我没有测试过这一点,但这样的:
def everythird():
queryset = get_foo(person) #First queryset
promoted_foo = get_promoted_foo() #Second queryset
for (counter,(s,p)) in enumerate(itertools.izip(queryset,promoted_foo)):
if counter%3==0 and promoted_foo:
yield promoted_foo
elif queryset:
yield queryset
答
有没有需要遍历查询集或promoted_foo,如果你不打算使用返回的值。你也不应该修改你在循环中迭代的容器。
另一种方法是:
# For a range with step size 3, from 0 until the length of the shortest container.
for idx in xrange(0, min(len(queryset), len(promoted_foo), 3):
queryset.insert(idx, promoted_foo.pop())
if promoted_foo:
queryset.extend(promoted_foo)
PS。您在queryset上使用insert()意味着它已经是一个列表。
我认为'对于行qs:yield row'会更好 – Shaung 2012-07-21 12:54:54