MODELS AND MIGRATIONS
We will see in this post after the creation of a news application, how it is possible to define through classes and OOP entities (classes) that
they represent the conceptual model of our App. We will do this by writing the models.py file of our application. Once the conceptual model has been written and its relationships established, we will create the Sqlite database using the migration mechanism.
Let’s start by creating a new virtual environment, after creating the root folder that I called secondlevel. We issue the following commands to create and activate the environment.
python -m venv venv (environment creation venv)
venv\Scripts\activate (activation of venv)
After creating the virtual environment, install Django with the command:
pip install django
Now let’s create the project with the following command:
django-admin startproject DjangoSecondLevel
I entered DjangoSecondLevel as the name of the project, you can choose any name. At this point we start the development server to check that everything is working correctly. Let’s go to the directory containing manage.py and start the server.
python manage.py runserver
As you can see, the installation was successful, however there is a small detail to fix. The tongue. Let’s go to the settings.py file of the project and scrolling down we find the entry LANGUAGE_CODE. We set this value to “it”. Let’s restart the server and this time the contents will appear in our language.
Now let’s create the news application with the following command:
python manage.py startapp news
We install the app by adding it to the list of apps pre-installed by Django by going to the project’s settings.py file under INSTALLED_APPS.
Now let’s get to the heart of our post and open the models.py file of the news application. This very important file allows us to map the created classes (entities) with the database structure that will be modeled according to what is defined in it. Now a news application has at least two classes to make it easier, the Articolo class and the Giornalista class, that is, the one who writes the articles. The code that I will now explain is given below.
from django.db import models # Create your models here. class Giornalista(models.Model): nome = models.CharField(max_length=20) cognome = models.CharField(max_length=20) def __str__(self): return f'({self.nome} + {self.cognome})' class Articolo(models.Model): titolo = models.CharField(max_length=100) contenuto = models.TextField() giornalista = models.ForeignKey(Giornalista,on_delete=models.CASCADE,related_name='articoli') def __str__(self): return self.titolo
EXPLANATION OF THE CODE
The Giornalista and Articolo classes will become the tables of our database, while the attributes such as nome and cognome will become the columns. The type of model fields depends on the length of the attributes, for nome and cognome a CharField (remember that for this type of data you must specify the length with max_length) it is fine, while for the contenuto of an Articolo, which can be full-bodied, we choose the TextField type (refer to the documentation for all the various types of fields supported by Django). Let’s now explain the ForeignKey.
RELATIONS
There is obviously a relationship between Journalist and Article. To build this relationship Django provides us with the ForeignKey defined in the Articolo class in the giornalista attribute that allows us to know that article by whom it was written. (Many-to-one relationship a Journalist can write many articles). on_delete specifies what Django should do when a Giornalista is deleted. The CASCADE attribute indicates that his articles must also be deleted together with the Giornalista. related_name allows us to go back to the inverse relationship, that is, from the Giornalista to go and see all the articles he has written. Finally, keep in mind that Django automatically implements the primary key of the tables, which is a unique numeric identifier (id) that automatically increments.
MIGRATIONS
Now that we have built the model we need to create the tables in the database through the migration mechanism. To do this we issue the following commands.
python manage.py makemigrations (create sql commands to send to db)
python manage.py migrate (create sqlite database structure)
We can see the migration with the command
python manage.py sqlmigrate news 0001
I recommend that you download the DB Browser (sqlite) program to actually see the database created.
Leave A Comment