Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

python - Django circular model reference

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...