Summary
Now let's collect all the knowledge we have gained in one chapter.
Models
A Model is a class that represents a table from the database.
Model class structure
Model class should be inherited from the Model
class.
pythonclass NewModel(models.Model):
The structure of the Model class should be filled in by Field objects.
python# Exampleattribute = models.IntegerField()
Note
Some fields have non-optional parameters (arguments).
Command for Migrations
pythonpython manage.py makemigrationspython manage.py migrate
Note
Try the
python3
if thepython
doesn't work.
Instances
To work with instances, you need to use different methods.
Create
- Create a new Model class instance.
- Fill in all necessary attributes.
- Submit changes using the
save()
method that send a query to the database.
pythonpost = Post()post.title = "Title"post.text = "Text"post.save()
Retrieve all
Return the iterable QuerySet containing database records.
pythonposts = Post.objects.all()
Retrieve one
Return the one database record as the Model class instance.
pythonpost = Post.objects.get(pk=pk)
Update
- Retrieve data.
- Reassign attributes of the Model class instance(s).
- Submit changes using the
save()
method that send a query to the database.
pythonpost = Post.objects.get(pk=pk)post.title = "New Title"post.text = "New text"post.save()
pythonposts = Post.objects.all()for post in posts:post.title = "New Title"post.text = "New text"post.save()
URL patterns
To receive the pk
from the URL address, we need to use the specific syntax: <int:pk>
, where:
int
is a type of value;pk
is the name of the argument in the view function.
¡Gracias por tus comentarios!