Reputation: 1148
I need to append information to an object in Django rather than update it. I have this database:
Database:
-----------------------
ColA | ColB
-----------------------
1 | "Test string."
And the code that updates:
o = Model.objects.select_related().filter(ColA=1).update(
ColB = "Entry 2")
This will set ColB
to Entry 2
. I want to be able to append rather than update. Is there a way I can append the text so that ColB
will be set to "Test string. Entry 2."
?
Upvotes: 1
Views: 3705
Reputation: 599610
You can, but it's a bit fiddly.
from django.db.models import Value
from django.db.models.functions import Concat
Model.objects.select_related().filter(ColA=1).update(ColB=Concat('ColB', Value('Entry 2')))
It's probably easier to just get the item, modify it, and save it:
o = Model.objects.get(ColA=1)
o.ColB += "Entry 2"
o.save()
Upvotes: 5
Reputation: 1601
objects = Model.objects.select_related().filter(ColA=1)
for o in objects:
o.colB = o.colB + ' Entry 2.'
o.save()
Upvotes: 0