Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Summary | Working with Database
Django: First Dive

book
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.

python
class NewModel(models.Model):

The structure of the Model class should be filled in by Field objects.

python
# Example
attribute = models.IntegerField()

Note

Some fields have non-optional parameters (arguments).

Manager

Manager allows tools to manipulate the data.

python
objects = models.Manager()

Command for Migrations

python
python manage.py makemigrations
python manage.py migrate

Note

Try the python3 if the python doesn't work.

Instances

To work with instances, you need to use different methods.

Create

  1. Create a new Model class instance.
  2. Fill in all necessary attributes.
  3. Submit changes using the save() method that send a query to the database.
python
post = Post()

post.title = "Title"
post.text = "Text"

post.save()

Retrieve all

Return the iterable QuerySet containing database records.

python
posts = Post.objects.all()

Retrieve one

Return the one database record as the Model class instance.

python
post = Post.objects.get(pk=pk)

Update

  1. Retrieve data.
  2. Reassign attributes of the Model class instance(s).
  3. Submit changes using the save() method that send a query to the database.
python
post = Post.objects.get(pk=pk)

post.title = "New Title"
post.text = "New text"

post.save()
python
posts = 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.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 5
some-alt