RabbitInAHole
RabbitInAHole

Reputation: 581

Update queryset attribute value without losing order on that attribute

class Foo(models.Model):
    value = models.IntegerField()

    class Meta:
        ordering = ('value',)

Consider this queryset:

[<Foo pk=1 value: 0>, <Foo pk=3 value: 2>, <Foo pk=2 value: 5>]

What would be a good way to update the queryset to look like this:

[<Foo pk=1 value: 0>, <Foo pk=3 value: 1>, <Foo pk=2 value: 2>]

So basically I want all instances to maintain their ordering, but update the entire queryset so that every instance uses its lowest possible value to keep the hierarchy which would basically come down to:

>>> range(0, qs.count())
[0, 1, 2]

I suppose I could work with the range above, then find the Max in my queryset update it by calling pop() on my range, until my range is empty, but this seems inefficient

Upvotes: 0

Views: 28

Answers (1)

Vikas Ojha
Vikas Ojha

Reputation: 6950

Hope the following helps:

for i, record in enumerate(qs):
    record.value = i

Upvotes: 1

Related Questions