Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django circular model reference

Tags:

I'm starting to work on a small soccer league management website (mostly for learning purposes) and can't wrap my mind around a Django models relationship. For simplicity, let's say I have 2 types of objects - Player and Team. Naturally, a player belongs to one team so that's a ForeignKey(Team) in the Player model. So I go:

class Team(models.Model):     name = models.CharField() class Player(models.Model):     name = models.CharField()     team = models.ForeignKey(Team) 

Then I want each team to have a captain which would be one of the players so that would be a ForeignKey(Player) in the Team model. But that would create a circular dependency. Granted my Django experience is limited, but it seems like a simple problem, though I can't figure out what I'm doing wrong conceptually.

like image 852
exfizik Avatar asked Dec 11 '11 19:12

exfizik


People also ask

What is circular dependency Django?

A circular dependency occurs when two or more modules depend on each other. This is due to the fact that each module is defined in terms of the other (See Figure 1). For example: functionA(): functionB() And functionB(): functionA() The code above depicts a fairly obvious circular dependency.

What causes circular import in Django?

Generally, the Python Circular Import problem occurs when you accidentally name your working file the same as the module name and those modules depend on each other. This way the python opens the same file which causes a circular loop and eventually throws an error.

What are signals in Django?

Django includes a “signal dispatcher” which helps decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place.


1 Answers

as you can see in the docs, for exactly this reason it is possible to specify the foreign model as a string.

team = models.ForeignKey('Team') 
like image 88
second Avatar answered Oct 03 '22 22:10

second