realshadow
realshadow

Reputation: 2585

Django queryset update field increasing/descreasing its current value

I am trying to change order of nodes in my tree. Everything works fine, but I would like to know if there is some beautiful, easy way of updating multiple fields by increasing its actual value by 1. Let me illustrate.

Objtree.objects.select_related().filter(pk__in = ids).update(sort_order = 1)

This code will change every sort_order column value to 1, but I would like to change it to something like:

Objtree.objects.select_related().filter(pk__in = ids).update(sort_order += 1)
# or
Objtree.objects.select_related().filter(pk__in = ids).update(self.sort_order = 1)

So... is there something like that? Nothing comes to my mind or my screen via googling.

Thanks for halp!

Upvotes: 20

Views: 15359

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You want to use F() objects.

from django.db.models import F
Objtree.objects.filter(pk__in=ids).update(sort_order=F('sort_order')+1)

See the documentation

Upvotes: 41

Related Questions