ID | Name | Age |
---|---|---|
1 | Anton | 34 |
2 | Morten | 37 |
ID | Subject | Hours |
---|---|---|
1 | Python | 30 |
2 | Matlab | 0 |
ID | HumanName | HumanAge | CourseSubject | CourseHours |
---|---|---|---|---|
1 | Anton | 34 | Python | 30 |
2 | Morten | 37 | Python | 30 |
ID | HumanID | CourseID |
---|---|---|
1 | 1 | 1 |
2 | 2 | 1 |
Field | Type |
---|---|
ID | Integer |
Name | String |
Age | Integer |
Field | Type |
---|---|
ID | Integer |
Subject | String |
Hours | Integer |
Field | Type |
---|---|
ID | Integer |
human | Integer |
course | Integer |
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)
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()
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]
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()
In [ ]:
teachers = Teacher.objects.all()
t0 = teachers[0]
print t0.human.name
print t0.human.age
print t0.course.subject
print t0.course.hours
In [ ]:
theTeacher = Teacher.objects.find(human__name__contains='An')
theTeacher[0]