DATABASE API
Before dealing with the views, let’s see how to interact further with the database, add data, modify them, delete them, make filters etc. Django provides APIs that allow us to interact with the database at a higher level than SQL (Structure Query Language).
LET’S BEGIN!
We open our project and in the terminal we type the following command:
python manage.py shell
This command is used to open a shell where we will type commands. First of all, let’s import the Giornalista entity with the following command.
from news.models import Giornalista
to insert a new row in the database we type the following command:
g1 = Giornalista(nome=’Mario’, cognome=’Rossi’)
g1.save() //save the record in the database
To see the content just type the name of the instance variable for example g1. To view all the contents entered, just write:
Giornalista.objects.all()
We can see the attributes of the individual instances by typing for example:
g1.nome
g1.cognome
Also, you can create instances without using the save() method with the following command:
Giornalista.objects.create(nome=’Pinco’, cognome=’Pallo’)
The primary keys allow us to go and find a particular Giornalista as in the following example:
Giornalista.objects.get(id=1)
You can use both id and pk (primary key)
We can make filters such as, for example, filter all giornalisti named Mario.
Giornalista.objects.filter(nome=’Mario’)
We can exclude entities with the following command:
Giornalista.objects.exclude(cognome=’Rossi’)
We can make a cycle on the inserted records as shown in the figure:
UPDATE
DELETE
The same goes for the articles, they are imported using the command
from news.models import Articolo
The difference is that a relationship represented by the giornalista attribute has been specified in the Articolo entity. When we insert an articolo, in addition to specifying a title and content, we must also specify the request of the Giornalista who wrote it. Let’s see an example.
LE VIEW IN DJANGO
We create the view in the views.py folder of the news application. Once the Articolo and Giornalista entities have been imported from the models we are ready to build our homepage by populating the information through the API just seen directly from the database. Once the home is built, go to the project’s urls.py file and map the resource to localhost:8000.
Leave A Comment