DATABASE API

Django

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

Database API
Database API
Database API

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

shell 1

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

shell 2

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()

shell 3

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’)

shell 4

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)

shell 5

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:

shell 6

UPDATE

shell 7

DELETE

shell 8

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.

shell 9

LE VIEW IN DJANGO

Views
Views

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.

Code Views.py
urls.py

LINKS TO PREVIOUS POST

PREVIOUS POST LINKS

LINK TO THE CODE ON GITHUB

GITHUB