0

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.

2
  • Please post the code for your form. Commented Jan 19, 2017 at 18:09
  • 1
    See also UpdateView Commented Jan 19, 2017 at 22:03

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

Keep in mind calling .update() will skip your .save() method which sometimes includes some functionality
Try also: Model.objects.filter(x=value0).update(column=value, column2=value2)
That looks a lot cleaner, thanks. What do you mean by the first comment? Is using .update() worse than using a .save() by any means? I', still new to Django and learning my way around.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.