Course Content
Django: First Dive
Django: First Dive
2. Write the First Page
4. Working with Database
Update and Delete Data
Update data
If you had no problems with the Create and Retrieve operations, you should be able to easily understand the logic of updating data. Let's break down the logic into certain steps:
- Extract the object and write it in a variable.
- Reassign attributes.
- Save the changes using the
save()
method
Let's look at the example.
URL pattern
View function
Result
The provided code updates the Post
using pk
(id
) received from the URL address.
Delete Data
To delete data, you just need to extract data and use the delete()
object method.
URL pattern
View function
Result
You can see that None
is displayed instead of post id
. The fact is that the object was already deleted by the delete()
method, and, accordingly, it does not have an id
because it is no longer in the database.
To display the id
of the deleted object, you can store it in a variable and then output it using HttpResponse
.
Everything was clear?