anon
anon

Reputation:

Django how to update more than a row field at once

The code below would be fine for updating a row field:

t = TheForm.objects.get(id=1)
t.value = 1
t.save() 

But what if I need to update 5-6 fields at once? Is there any direct way?

Like update (value=1,value2=2)

EDIT

I already know that I can do:

t.value1 = 1
t.value2 = 1
t.value3 = 1 

But I am looking for a single line command like the Insert one for instance. (TheForm(value1=1,value2=2,value3=3))

Upvotes: 0

Views: 74

Answers (2)

Alasdair
Alasdair

Reputation: 308879

You can change as many fields as you want before you save.

t = TheForm.objects.get(id=1)
t.value1 = 1
t.value2 = 2
t.save() 

You can also use the update method:

t = TheForm.objects.filter(id=1).update(value1=1,value2=2)

Note that using update is subtlety different. There wont be an error if the object with id=1 does not exist. Pre- and post-save signals won't be sent when using update.

Upvotes: 0

Thomas Orozco
Thomas Orozco

Reputation: 55197

Sure!

t.value1 = 1
t.value2 = 2
t.save()

Alternatively,

TheForm.objects.filter(id=1).update(value=1, value2=2)

(And you could use **kwargs here)

Upvotes: 3

Related Questions