Home

Search IconIcon to open search

Django models

ManyToMany is a cool feature!

Use through= to explicitly define the intermediate table:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.db import models
 
class Course(models.Model):
    name    = models.CharField(max_length=30)
 
class Student(models.Model):
    name    = models.CharField(max_length=30)
    courses = models.ManyToManyField(Course, through="Enrollment")
 
class Enrollment(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    course  = models.ForeignKey(Course, on_delete=models.CASCADE)
    date    = models.DateField()
    mark    = models.IntegerField(max_value=5)