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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With