I want to create an object that contains 2 links to Users. For example:
class GameClaim(models.Model):
target = models.ForeignKey(User)
claimer = models.ForeignKey(User)
isAccepted = models.BooleanField()
but I am getting the following errors when running the server:
-
Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.
-
Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.
Can you please explain why I am getting the errors and how to fix them?
Best Answer
You have two foreign keys to User. Django automatically creates a reverse relation from User back to GameClaim, which is usually
gameclaim_set
. However, because you have two FKs, you would have twogameclaim_set
attributes, which is obviously impossible. So you need to tell Django what name to use for the reverse relation.Use the
related_name
attribute in the FK definition. e.g.