ordering a query set randomly

51 views
Skip to first unread message

Orcun Avsar

unread,
Oct 17, 2008, 1:46:14 PM10/17/08
to Django users
hi,
problem is that i want to order model instances for an attribute and
slice it. then sort list randomly.

>>query=order_by("date")[:20]
>>query.order_by("?")
returns an error because query set has been sliced


>>query=order_by("date")[:100]
>>random.shuffle(query)
also returns error bacuse query set doesn't behave like a list and
doesn't support item assignment.

dirty solution was creating a list contains model instances by putting
query in a for loop then shuffle it. is there any alternative solution.

Steve Holden

unread,
Oct 17, 2008, 1:54:06 PM10/17/08
to django...@googlegroups.com

A much cheaper solution would be to create a list of range(20),
randomize that with shuffle and use successive elements to index the slice.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Reply all
Reply to author
Forward
0 new messages