from django.db import models # Utils function to truncate my string when it's too long (use in to string method) def truncate_string(text): if len(text) > 15: return text[:15] + "..." else: return text class Course(models.Model): # Defining choices for the course level BEGINNER = "B" INTERMEDIATE = "I" ADVANCED = "A" LEVELS_CHOICES = [ (BEGINNER, "Beginner"), (INTERMEDIATE, "Intermediate"), (ADVANCED, "Advanced"), ] # Defining our attributes which equal the Course table's columns title = models.CharField(max_length=200) summary = models.CharField(max_length=1000) level = models.CharField(choices=LEVELS_CHOICES, default=BEGINNER, max_length=12) places = models.IntegerField(default=0) teacher = models.ForeignKey('Person', on_delete=models.CASCADE, related_name='teacher', limit_choices_to={'role': 'Teacher'}) students = models.ManyToManyField('Person', blank=True, related_name='students', limit_choices_to={'role': 'Student'}) # Utils function def __str__(self): return self.title + " " + truncate_string(self.summary) def getLevel(self): if (self.level == "B"): return "Beginner" if (self.level == "I"): return "Intermediate" return "Advanced" # Student or teacher, what differs? For teachers, courses will be the courses taught, and for students, the courses followed. # However, this only deferrs into a 'role'. If it's a teacher, then the courses are taught, else they are followed. # All the logic can be simplified with the role attribute. Later, we'll also be able to check permission with this attribute. class Person(models.Model): # Defining choices for the course level STUDENT = "Student" TEACHER = "Teacher" ROLE_CHOICES = [ (STUDENT, "Student"), (TEACHER, "Teacher"), ] # Defining our attributes which equal the Course table's columns name = models.CharField(max_length=200) role = models.CharField(choices=ROLE_CHOICES, default=STUDENT, max_length=7) # Return the courses list for the Person # If it's a teacher, returns all courses he teaches # If it's a student, returns all courses he follows @property def courses(self): if (self.role == "Student"): return [course for course in Course.objects.all() if self in course.students.all()] return Course.objects.filter(teacher=self) # Utils function def __str__(self): return self.name + " is a " + self.role