La base dati in Django
Creazione di un primo modello
La descrizione del modello va inserita nel file didattica/models.py
class Professor(models.Model):
slug = models.CharField(max_length=30, primary_key=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __str__(self):
return self.slug
class Course(models.Model):
slug = models.CharField(max_length=30, primary_key=True)
title = models.CharField(max_length=50)
teacher = models.ForeignKey(Professor)
def __str__(self):
return self.slug
Aggiornamento del DB
Django gestisce l'aggiornamento del DB, senza perdita di dati, tramite i seguenti comandi
python manage.py makemigrations
python manage.py migrate
L'output dovrebbe essere come segue:
Migrations for 'didattica':
0001_initial.py:
- Create model Course
- Create model Professor
- Add field teacher to course
e
Operations to perform:
Apply all migrations: admin, didattica, contenttypes, auth, sessions
Running migrations:
Rendering model states... DONE
Applying didattica.0001_initial... OK
Interazione con il DB
Django permette di utilizzare la shell interattiva di Python tramite il comando python manahe.py shell
Possiamo utilizzarla per manipolare il DB:
from didattica.models import Professor, Course
prof1 = Professor(slug='CANDIOTTO', first_name='Roberto', last_name='Candiotto')
prof1.save()
course1 = Course(slug='OA', title='Organizzazione Aziendale', teacher=prof1)
course1.save()
oppure possiamo introdurre dei dati attraverso l'interfaccia di amministrazione http://127.0.0.1:8000/admin/ dopo aver registrato i modelli modificando il file didattica/admin.py come segue:
from didattica.models import Professor, Course
# ...
admin.site.register(Professor)
admin.site.register(Course)
Dopo aver aggiunto qualche dato nel DB possiamo interrogarlo dalla shell python manahe.py shell
:
from didattica.models import Professor, Course
director = Professor.objects.get(last_name='Candiotto');
all_courses = Course.objects.all()
director_courses = Course.objects.filter(teacher=director)
print vars(director_courses[0])