using django models to map one to many and many to one

86 Views Asked by At

I started using django today and am having trouble creating models based off the response of an API call. We can have a Course that gives a list of professors. Though, Professors can also teach multiple courses. I'm not sure how to create a list for both professors in the Course class and courses in the Professor class. Note: I am using MongoDB so I wasn't using the postgres ArrayFields. I have the following code:


from django.db import models


class Course(models.Model):
    department = models.CharField(max_length=4)
    course_number = models.CharField(max_length=4)
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=1000)
    credits = models.IntegerField(max_length=1)
    gpa = models.DecimalField(max_digits=4, decimal_places=3)
    professors = ???


class Professor(models.Model):
    id = models.CharField(max_length=50, unique=True)
    name = models.CharField(max_length=100, unique=True)
    reviews = models.BooleanField(default=True)
    courses = ???

I visited this stackoverflow post and wasn't sure if this was the best way to approach it considering this might be a bit outdated.

I also viewed the ArrayFields class to attempt to use that but wasn't sure if that was only for postgres (because I'm using MongoDB)

1

There are 1 best solutions below

0
On

First of all, it is not necessary to add the field id in the Professor Model because Django automatically does it.

About your question, you could create a new Model, for example called Teaching with the association Professor-Course:

class Teaching(models.Model):
    course = models.ForeignKey(Course, on_delete=models.DO_NOTHING)
    professor = models.ForeignKey(Professor, on_delete=models.DO_NOTHING)