简体   繁体   中英

django queryset able update own model's field with existing value + 1?

sorry if the title does not make too much sense, I am not sure how to put it in a correct way with only little words.

Anyways, what I really want is...I know we can filter querysets then use update to update all the fields in the queryset without doing a loop then save()

But what I really need here is something like......

User.objects.filter().update(username=this is where I want to update BUT I want to update itself's username+1)

if I do it in a loopie way, it'll be something like

all_users = User.objects.filter()
for user in all_users:
    user.username = user.username + str(1)
    user.save()

but is there a way to use update and do that?

Thanks in advance for any help.

It's possible to do it with F() from django.db.models

from django.db.models import F
User.objects.filter(pk=pk).update(new_attr=F('username')+str(1))

or

all_users = User.objects.filter()
for user in all_users:
   user.username =  F('username') + str(1)
   user.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM