Should I use Many-to-one relationship or a Many-to-many?

Basically I am creating a website using django where I have created a class called courses and a separate class Class. I'm now confused which relationship I should use.

My code:

class Class(models.Model):
    title = models.CharField(max_length=100)
    video = models.FileField(upload_to='class/class_videos',null=True,
validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])])


    def __str__(self):
        return self.name


class Course(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(upload_to='class/instructor_pics', null=True)
    instructor = models.CharField(max_length=100)
    instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True)
    students = models.ManyToManyField(User, related_name='courses_joined', blank=True)
    slug = models.SlugField(max_length=200, unique=True)
    description = models.TextField(max_length=300, null=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created']

    def __str__(self):
        return self.title

Thanks in advance!

Thinking about your problem, each Class can only belong to one course, but each course can have multiple classes correct?

If that's the case then you should have a many to one where many is the class and the course is the one.

You already have it somewhat in your code

students = models.ManyToManyField(User, related_name='courses_joined', blank=True)
classes = models.OneToManyField(Class, related_name='...')

Just add the line classes = models.ForeignKey(Class, on_delete=models.CASCADE, null=True)

I reckon that the course will be divided into classes. So, the Class model will contain a ForeignKey field that points to the Course model.

More precisely, this is what OP will want

class Class(models.Model):
    course = models.ForeignKey(Course, related_name='classes', on_delete=models.CASCADE)
Back to Top