Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python/django list.reverse() and reversed(list)

I tried this today in my django console and I got two different results. I thought that list.reverse() reverses the list (ie first object becomes last and so on)[1]. However it does not seem the case.

>>> from django.db.models import Q
>>> q1 = Q(result=1)
>>> q2 = Q(result=-1)
>>> q3 = q1 | q2
>>> form = UserData.objects.filter(user=user).filter(coins__gt=0).filter(q3).order_by('-modified', '-placed').values_list('result', flat=True)[:10]
>>> form
Out[14]: [-1, -1, -1, -1, -1, 1, -1, 1, -1, -1]
>>> form.reverse()
Out[15]: [1, 1, 1, 1, 1, 1, 1, -1, -1, -1]
>>> form_bw = []
>>> for f in reversed(form):
...     form_bw.append(f)
...     
>>> form_bw
Out[18]: [-1, -1, 1, -1, 1, -1, -1, -1, -1, -1]

What am I doing wrong? Obviously what I want is form_bw

[1] http://docs.python.org/tutorial/datastructures.html

like image 603
xpanta Avatar asked May 01 '12 08:05

xpanta


Video Answer


1 Answers

When you do

querysert.order_by('-modified', '-placed').reverse()

it actually means

querysert.order_by('modified', 'placed')

Thus if the result is unexpected, simply reverse in Python

list(reversed(values_list))

Or you have to check the ordering logic the reverse brought to the queryset.

like image 189
okm Avatar answered Oct 21 '22 19:10

okm