Contenido del Curso
Django: First Dive
Django: First Dive
Create Data
In this section, we will consider the 4 main operations with the database (CRUD):
- Create data.
- Retrieve data.
- Update data.
- Delete data.
As mentioned earlier, instances of the Model class are records in the table of the database.
Note
To work with the database, you need to understand one thing: the code of our project runs independently of the database, so any changes in the database must be submitted.
For instances of the Model class, the save()
method is a way to submit changes in data in the database.
Changes in database structure | Changes in data |
---|---|
Migrations | Submits |
makemigrations and migrate in Terminal | The save() method for the instances of Model class |
We implement the Post
model. As you know, in any social network, there are posts that users use, so this example will be useful because it can often be used in real development.
First, we need to implement the model of posts.
Note
Do not forget about migrations.
A new table is created empty. Let's consider how it can be filled.
As you already remember, Views are functions (or classes) that execute when receiving an HTTP request. Now let's create a new View inside the views.py
file to execute the code using the IDE to better consider working with the database.
The provided code defines a function named post_create
that handles a request and performs the creation of a new post in a database. The code creates a new instance of the Post
model, sets the title
and text
attributes of the post, saves it to the database using the save()
method, and finally returns an HTTP response with the message "Complete!" rendered as a level one heading.
Note
- The
save()
method submits changes and applies them to the database.- The post
id
is defined whensave()
method is executed.
Now we need to connect this view to the URL.
In the urls.py
file let's write the following URL pattern:
The provided code configures URL routing. It imports the post_create
view function from the new_app.views
module. URL pattern is defined, which maps the URL path posts/create/
to the post_create
view function, and assigns the name "post-create"
to this URL pattern for easy reference in other parts of the Django project.
Overview
Let's run server and see the result using the http://127.0.0.1:8000/post/create/
URL.
The header has returned, so the View is executed. Let's look at the database.
You can see the record in the database was created.
Let's repeat our request to the same URL.
We added 4 of the same posts. Now you know how to fill the database.
Conclusion
The steps to add record in the database:
- Import the Model class.
- Create the instance of this Model class.
- Fill in the attributes of this instance.
- Use the
save()
method to apply changes.
¡Gracias por tus comentarios!