'DJANGO: Mass update field by adding a prefix
I wish to update a Django model field of objects in a queryset. To be specific, I want to add a prefix on one of the fields i.e. if an object has a name like 'Wilson', I want to prefix it with 'OLD', then it will become 'OLDWilson'.
I can think of the following using loops:
my_objs = MyObjects.objects.filter(name='some_name') # This has over 40000 records
for obj in my_objs:
obj.name = 'OLD{0}'.format(obj.name)
obj.save()
I was hoping of a more elegant way to take advantage of the UPDATE
method as specified here: Django Mass Update
Something like the following:
MyObjects.objects.filter(name='some_name').update(name='OLD+name_here')
Any pointers on how I can achieve this?
Solution 1:[1]
I know this question is almost 5 years old. But, with hopes that this helps the answer be more visible - here goes.
Use Concat from django.db.models.functions like so:
from django.db.models.functions import Concat
from django.db.models import Value
MyObjects.objects.filter(name='some_name').update(name=Concat(Value'OLD', 'name'))
That last line returns the number of rows affected by the update.
Solution 2:[2]
This actually works in the latest version of Django as of May 2022
from django.db.models import Value
from django.db.models.functions import Concat
query = MyObjects.objects.filter(name='some_name')
query.update(name=Concat(Value("OLD"), "name"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dennis Bottaro |
Solution 2 | Chrisjan |