How do I work around 'circular import' in Django?

Viewed 27

I'm getting a 'circular import' error when trying to makemigrations in Django. The two models in question are these. The error is being flagged on Team.

from django.db import models
from django.contrib.auth.models import User
from footballapi.models.team import Team
from footballapi.models.bio import Bio

class Player(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.ForeignKey(Bio, on_delete=models.CASCADE)
    teams = models.ManyToManyField(Team, on_delete=models.CASCADE, related_name="members")


from django.db import models
from footballapi.models.player import Player

class Team(models.Model):
    name = models.CharField(max_length=50)
    roster_spot = models.ForeignKey(Player, on_delete=models.CASCADE)

I think the issue is with the ManyToManyField, and I keep reading that I should use a string instead of the import. But I've tried every combination of words and can't find the right string. What should it be? By the way, these models are all from the same app.

1 Answers

Besides the classes you can also use a string "app_name.model_name" for a foreignkey relationship thus avoiding to import each other.

teams = models.ManyToManyField("app_name.Team", on_delete=models.CASCADE, related_name="members")

Alternatively, you could change your datamodel with a through table in your m2m relationship. Using this table you could set a boolean indicating if a player is playing roster_post. Check out the docs: https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.ManyToManyField.through

Related