[Answer]-When should we use ForeignKey and ManyToOne in django

1đź‘Ť

Your model with foreign key looks like right if there cannot be a department divided into many colleges. If a department can be divided into a many colleges, you’ll have to set a ManyToMany with a “through” argument, and in the trough model add a “unique_together” like bellow:

For the FK, to add your constraint, you should change Dept as follows:

class Dept(models.Model):
    name = models.CharField(max_length=200)
    uid = models.CharField(max_length=10)
    college = models.ForeignKey(College)

    class Meta:
        unique_together = (('name', 'college'),)
👤Ricola3D

Leave a comment