#Incrementing multiple objects using a prefix dependent on how many they are

13 messages · Page 1 of 1 (latest)

raven hamlet
#

I am trying to write something like this:

somequeryset.order_by("some_field").update(rank="...")

where the "..." is such that all the objects in the queryset have their field "rank" set to a value that is an enumeration of the position of the objects in order determined by the order_by() method. That is, if the order is object_1, object_2, ..., object_n I would like to have their rank field reflect the order, so that object_1.rank = 1, object_2.rank = 2, etc.

Is it possible?

worldly hearth
raven hamlet
worldly hearth
raven hamlet
#

Thanks, so the enumeration would be done in plain Python? There's no ORM/Postgres way to do it?

worldly hearth
#

Otherwise you might by able to use the RowNumber expression in an annotate with F expressions.

worldly hearth
#

And worst case, you can use raw sql

raven hamlet
#

I guess I'll need to see if any of the two approaches fares much better, benchmark-wise.

worldly hearth
#

You're right to avoid pulling it into python if possibile. But if it's a large dataset, things might get hairy updating that much data.

raven hamlet
#

true that. Thanks very much, that helped!

worldly hearth
#

You're welcome. If there's a bug difference between the two let me know. I'm curious now

raven hamlet
#

@worldly hearth By the way I see you're a mod. Perhaps it would be nice to let posts on these forums be mark-able as "solved my issue". 😁