Relational database

A lot of data can be stored in tabels

Table Human

ID Name Age
1 Anton 34
2 Morten 37

Table Course

ID Subject Hours
1 Python 30
2 Matlab 0

Table Teacher (wrong)

ID HumanName HumanAge CourseSubject CourseHours
1 Anton 34 Python 30
2 Morten 37 Python 30

Table Teacher (correct)

ID HumanID CourseID
1 1 1
2 2 1

How to present structure of tables

Table Human

Field Type
ID Integer
Name String
Age Integer

Table Course

Field Type
ID Integer
Subject String
Hours Integer

Table Teacher

Field Type
ID Integer
human Integer
course Integer

How to define structure of tables in Python? Django Models!


In [ ]:
# models.py
from django.db import models

class Human(models.Model):
    ''' Description of any Human'''
    name = models.CharField(max_length=200)
    age  = models.IntegerField()

    objects = models.Manager()

    def __str__(self):
        ''' Nicely print Human object '''
        return u"I'm %s, %d years old" % (self.name, self.age)


class Course(models.Model):
    ''' Description of teaching course'''
    subject = models.CharField(max_length=200)
    hours = models.IntegerField()

    objects = models.Manager()

    def __str__(self):
        ''' Nicely print Course object '''
        return 'Course in %s, %d hrs long' % (self.subject, self.hours)


class Teacher(models.Model):
    ''' Description of Teacher '''
    human = models.ForeignKey(Human)
    course = models.ForeignKey(Course)

    objects = models.Manager()

    def __str__(self):
        ''' Nicely print Teacher object '''
        return '%s teaching %s' % (self.human.name, self.course.subject)

How to use the Django Models?

1. Let's add data to database


In [ ]:
from our_project.models import Human

# create a Human and add data
h = Human()
h.name = 'Anton'
h.age = 34

# save data to database
h.save()

2. Now we can quit python and enter again


In [ ]:
from our_project.models import Human

# fetch all Humans from the database
humans = Human.objects.all()

# get the first one (the only one so far)
h0 = humans[0]

3. Let's add more data and make a relation


In [ ]:
from our_project.models import Course, Teacher

In [ ]:
# we create and save a course
c = Course()
c.subject = 'Python'
c.hours = 30
c.save()

# we create a teacher
t = Teacher()

# we create relations
t.human = h0
t.course = c
t.save()

Now the database contains

  • three tables: Human, Course and Teacher
  • two relations: Teacher --> Human and Teacher --> Course

Let's fetch the data from the database.


In [ ]:
teachers = Teacher.objects.all()
t0 = teachers[0]
print t0.human.name
print t0.human.age
print t0.course.subject
print t0.course.hours

We can also search the database using a siple syntax


In [ ]:
theTeacher = Teacher.objects.find(human__name__contains='An')
theTeacher[0]