Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset update field increasing/descreasing its current value

Tags:

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!

like image 498
realshadow Avatar asked Sep 06 '10 14:09

realshadow


1 Answers

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

like image 128
Daniel Roseman Avatar answered Dec 05 '22 06:12

Daniel Roseman