Tuesday, 25 January 2022

CRUD operations

 

CRUD operations




When working with databases, there are 4 basic operations: creating (create), reading (read), editing (update), and deleting (delete). All 4 basic functions are called briefly CRUD - by the first letters of each operation. We have already met with reading from the database in the articles Get data from the database and Data filteringIn this article, we'll take a look at the remaining three operations and learn a little more about reading.

In this article, we will work with a model Post- a blog article:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)

    text = models.TextField()

This is the post model. It has a title title, and it is designated as unique - unique=TrueThis means that there cannot be two articles with the same title in the database, each must have its own unique title.

In real sites, the field is made unique slug, it is this field that forms the address of the article on the Internet, and therefore must be uniqueFor clarity of examples, we have made the field unique title.


Reading

If the post has a unique field, as titlein this case, it can be accessed directly via get():

title = "CRUD"
crud_post = Post.objects.get(title=title)

Such a notation is clearer and more convenient than using a filter Post.objects.filter(title=title)[0].

If a post with the title “CRUD” is not in the database, you will get an error:

models.DoesNotExist: Post matching query does not exist.

This is a normal exception and can be caught and handled , although there are some quirks .

Creation

To create a new post, there is a createThis is how a new post is created

Post.objects.create(title="Заголовок нового поста", text="Текст нового поста")

Now it is saved and lies in the database:

post = Post.objects.get(title="Заголовок нового поста")
print(post.title)
# Заголовок нового поста

Editing

To edit a post object, you must first pull it out of the database. For example, like this:

post = Post.objects.get(title="New post title
")

Now we have a post object postand we can change its attributes. This is what editing the header might look like:

post = Post.objects.get(title="New post title")
post.title = "Why mom?
"

But it won't work. Changes must be sent to the database, otherwise, they will be lost when the program ends. The method is responsible for saving .save():

post = Post.objects.get(title="New post title")
post.title = "Why mom?"
post.save()

Removal

You can delete both individual posts and entire selections - QuerysetThis is done using the method delete():

post = Post.objects.get(title="New")
post.delete()  # 

all_posts = Post.objects.all()
all_posts.delete()  # 




What is REST, RESTFul and CRUD

  What is REST, RESTFul, and CRUD REST  is a concept for component interaction based on the HTTP protocol.  I do not want to dwell on boring...