Django- manytomany model relationships

135 views Asked by At

I'm still learning about how to setup up relational databases. I'm trying to create a db that tracks universities, departments, and their programs. My question is a relationship one. Each university might have one or more departments. This relationship should then be a many to many. Each department may have one or more programs, so I can see the relationship between the department and the programs being many to many.

The problem that I have is if I want to have a department that belongs to a university, I feel like I should use an intermediary to attach a program to that department. But then, if I want to add another program to the same department, I would end up having two of the same departments belonging to the one university. This doesn't seem right.

In other words:

class Department(models.Model):
    '''
    '''
    code = models.CharField(max_length=80,unique=True)
    description = models.CharField(max_length=255)


    def __unicode__(self):
        return '{}'.format(self.description)


class Universities(models.Model):
    '''

    '''
    code = models.CharField(max_length=80,unique=True)
    description = models.CharField(max_length=255)
    departments = models.ManyToManyField(Department,through='UniversityHasDepartment')

class Program(models.Model):
    '''
    '''
    code = models.CharField(max_length=80,unique=True)
    description = models.CharField(max_length=255)

    def __unicode__(self):   
        return '{}'.format(self.description)

class UniversityHasDepartment(models.Model):
    university = models.ForeignKey(Universities)
    department = models.ForeignKey(Department)
    program = models.ForeignKey(Program)
1

There are 1 answers

2
quadlazer On

I think you want to use foreign keys. (one to many relationships).

Each university can have multiple departments but a department can only have 1 university. Each department can have multiple programs but a program can only have 1 department.

class University(models.Model):
    name = models.CharField(max_length=80,unique=True)
    description = models.CharField(max_length=255)

class Department(models.Model):
    university = models.ForeignKey(University, related_name='departments')
    name = models.CharField(max_length=80,unique=True)
    description = models.CharField(max_length=255)

class Program(models.Model):
    department = models.ForeignKey(Department, related_name='programs')
    name = models.CharField(max_length=80,unique=True)
    description = models.CharField(max_length=255)