Django ManyToManyField between 2 objects that point to one another

Viewed 783

In my project, I have 2 models with a ManyToMany field that point to each other. In this case, I have Elections and Candidates. The idea is that an Election can have multiple Candidates and that a Candidate can also be part of multiple elections (One 'Candidate' is only one person).

I have the following:

project/elections/models.py

from candidates.models import Candidate

class Election(models.Model):
    candidates = models.ManyToManyField(Candidate)
    ...

project/candidates/models.py

from elections.models import Election
    elections = models.ManyToManyField(Election)
    ...

When I try to run any command (makemigrations, runserver, etc.) I get a circular dependency between Election and Candidate which crashes. I have the models in different apps as a coding practice.

Should I:

  1. Move both models to one app and one file

  2. Not have the models pointing to each other (how would I then accomplish my goal?)

  3. Do something different

2 Answers

You do not need to do this. A many-to-many field is already bidirectional. Just define it on one side, and use the reverse relation.

To avoid circular dependency don't import the models, use strings instead, and include the applications name as namespace

project/elections/models.py

class Election(models.Model):
    candidates = models.ManyToManyField('candidates.Candidate')

Update

As the django docs points out, you only need to declare the relation on one of the models https://docs.djangoproject.com/es/2.1/topics/db/models/#many-to-many-relationships

It doesn’t matter which model has the ManyToManyField, but you should only put it in one of the models – not both.

Related