sherlock85
sherlock85

Reputation: 899

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).

Upvotes: 3

Views: 3358

Answers (1)

Rohan
Rohan

Reputation: 53366

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.

Upvotes: 5

Related Questions