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
pythonpath("posts/<int:pk>/update/", post_update, name="post-update")
View function
python912345678def post_update(request, pk):post = Post.objects.get(pk=pk)post.title = "Updated Post"post.text = "This post was updated"post.save()return HttpResponse(f"<h1>Post with id {post.id} updated</h1>")
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
pythonpath("posts/<int:pk>/delete/", post_delete, name="post-delete")
View function
python912345def post_delete(request, pk):post = Post.objects.get(pk=pk)post.delete()return HttpResponse(f"Delete Post (id {post.id})")
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
.
python9123456def post_delete(request, pk):post = Post.objects.get(pk=pk)post_id = post.id # newpost.delete()return HttpResponse(f"Delete Post (id {post_id})") # updated
1. Which method help us to submit changes (create and update) in the database?
2. Which method help us to delete record in the database?
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal