Django: Update order attribute for objects in a queryset
Posted
by lazerscience
on Stack Overflow
See other posts from Stack Overflow
or by lazerscience
Published on 2010-06-15T18:58:13Z
Indexed on
2010/06/15
19:02 UTC
Read the original article
Hit count: 258
I'm having a attribute on my model to allow the user to order the objects. I have to update the element's order depending on a list, that contains the object's ids in the new order; right now I'm iterating over the whole queryset and set one objects after the other. What would be the easiest/fastest way to do the same with the whole queryset?
def update_ordering(model, order):
""" order is in the form [id,id,id,id] for example: [8,4,5,1,3] """
id_to_order = dict((order[i], i) for i in range(len(order)))
for x in model.objects.all():
x.order = id_to_order[x.id]
x.save()
© Stack Overflow or respective owner