GreenSaber
GreenSaber

Reputation: 1148

Editing an Object in Database from Django Form

How can you edit an existing object in a database from a form? I use this for example:

obj_ex = Model(column = value, column2 = value2) obj_ex.save()

However this doesn't update my object in the database. I have tried to access the pk of the entry and save the values of the entry with the pk of x but I still can't update the table.

Is there a way to use an .update() type to update objects? Or is there another way to update a table?

Thank you.

Upvotes: 0

Views: 64

Answers (2)

GreenSaber
GreenSaber

Reputation: 1148

Because I had multiple entries in the table, I used an update field to updated the cells in the table. This is what I did:

o = Model.objects.filter(x=value0).values_list("id", flat=True) #where x is posted information getting the primary key (id).
Model.objects.select_related().filter(id = o).update(column = value, column2 = value2)

The update field does not need a .save() as it will update the table when it is called.

I would like to thank Udi for his answer as it did step me into the right direction.

Upvotes: 0

Udi
Udi

Reputation: 30472

Instead of:

obj_ex = Model(column=value, column2=value2)

Which creates a new instance (and later a new db record) try:

o = Model.objects.get(pk=1234)  # load instance with id=1234 to memory from db
o.column = value
o.column2 = value2
o.save()

Upvotes: 1

Related Questions