Home > Back-end >  Should I use Many-to-one relationship or a Many-to-many?
Should I use Many-to-one relationship or a Many-to-many?

Time:09-09

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!

CodePudding user response:

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

CodePudding user response:

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='...')
  • Related