3. Models

Django uses an ORM (Object-Relational Mapping) to interact with the database. This means that you can use Python to define your models and Django will take care of creating the tables in the database. It's super easy!

It is time to create a model in my_blog/models.py:

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=100)
    photo = models.ImageField(upload_to='photos/')
    description = models.TextField()
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Models are classes that represent tables in the database. Each attribute of the class is a field in the table. In this case, we have created an Article model with the fields title, photo, description, and date.

Now create the migration and apply the changes to the database. Open another terminal and run the following commands:

docker compose run --rm django python manage.py makemigrations
docker compose run --rm django python manage.py migrate

The database is now ready. Now let's add some articles.

In our next step we are going to enable the Django admin so that we can add articles from the web interface.

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.