Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - models - how to describe a specific bidirectional relation between two models?

I have two models: Person and Department. Each person can work in one department. Department can be run by many people. I'm not sure how to construct this relation in Django models.

Here's one of my unsuccessful tryings [models.py]:

class Person(models.Model):
     department = models.ForeignKey(Department)
     firstname = models.TextField(db_column='first_name')
     lastname = models.TextField(db_column='last_name')
     email = models.TextField(blank=True)

class Department(models.Model):
    administration = models.ManyToManyField(Person)
    name = models.TextField()

I am aware that the code does not work, because the Person class references the Department class in its ForeignKey relationship before the Department is defined. Likewise, if I move the Department definition before the Person definition, the Department class will reference the Person class in its ManyToMany relationships before the Person is defined.

What is the proper way to model this specific relation in Django? I would appreciate if you could provide the example (I'm a newbie).

like image 414
sherlock85 Avatar asked Dec 05 '25 14:12

sherlock85


1 Answers

You can put the model class name as string, as

class Person(models.Model):
     department = models.ForeignKey('Department')
     ....

First few lines of django doc on foreignkey relationship explain this.

like image 61
Rohan Avatar answered Dec 07 '25 04:12

Rohan