How to have two models reference each other Django How to have two models reference each other Django django django

How to have two models reference each other Django


The Django documentation for the ForeignKey field states:

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself.

So in your case, that would be:

class Game(models.Model):    # Other fields...    on = models.ForeignKey('Member', blank = True)class Member(models.Model):    # Other fields...    game = models.ForeignKey(Game)


You don't need to have the two models reference each other with foreign keys. Remove the line:

on = models.ForeignKey(Member, blank = True) #<----

and logically your Member's will still be associated to different Game's (and this makes more sense because a member can belong to one game at a time, whereas a game can have more than one member).

You can use reverse relation to figure out which members are on a particular game.