Reputation: 447
I am trying to traverse twice over one reversed object, initally the for loop works but not on the second loop.
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)
Upvotes: 1
Views: 253
Reputation: 477160
reversed(…)
[Python-doc] is an iterator, not an iterable, so the second time you loop, the iterator is already "exhausted". It is thus just a "shallow object", that "walks" through the QuerySet
in reversed order.
You thus use reversed(…)
twice. This will not make the query a second time, since the QuerySet
will cache the result, so:
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)
Upvotes: 1