繁体   English   中英

如何遍历 django 中的反向查询集?

[英]How to traverse over reversed queryset in django?

我试图在一个反向的 object 上遍历两次,最初 for 循环有效,但在第二个循环上无效。

x = Subscription.objects.filter(customer_id=customer_id).order_by('-id')[:count]
tmp = reversed(x)
y = call_function(subs=tmp) # inside this function as well object is of type reversed and i am able to loop over it inside the call_function.

for j in tmp: # this loop is not running at all. here as well tmp is a reversed object
    print(j)
# call_function(subs=s)
def call_function(s):
    for i in s:
       print(i)

reversed(…) [Python-doc]是一个迭代器,而不是一个迭代器,所以第二次循环时,迭代器已经“用尽”了。 因此,它只是一个“浅对象”,以相反的顺序“遍历” QuerySet

因此,您使用reversed(…)两次 不会进行第二次查询,因为QuerySet会缓存结果,所以:

x = Subscription.objects.filter(customer_id=customer_id).order_by('-id')[:count]
tmp = reversed(x)
y = call_function(subs=tmp)

for j in reversed(x):
    print(j)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM