Creating, Updating, and Deleting Records

Create

To create a new record, instantiate a model object and call .save():

new_post = BlogPost(title="New Post", content="This is a new post.", pub_date=date.today())
new_post.save()

Update

Updating a record is straightforward. Retrieve the record, modify its attributes, and call .save() again:

post_to_update = BlogPost.objects.get(title="Old Post")
post_to_update.content = "This post has been updated."
post_to_update.save()

Delete

Deleting a record is as simple as calling the .delete() method:

post_to_delete = BlogPost.objects.get(title="Post to Delete")
post_to_delete.delete()

Last updated