简体   繁体   中英

Add two ForeignKey Fields from same Model in Django

I'm trying to create a user and follower relationship as follows in Django

id | user_id | follower_id
1  | 20      | 45
2  | 20      | 53
3  | 32      | 20

For this, I've done the following:

class UserFollower(models.Model):
    user_id = models.ForeignKey(User)
    follower_id = models.ForeignKey(User)

    def __str__(self):
        return "{} following {}".format(self.follower_id.username, self.user_id.username)

where User is the django.contrib.auth.models.User model. On running makemigrations , I'm getting the following error:

ERRORS:
AppName.UserFollower.follower_id: (fields.E304) Reverse accessor for 'UserFollower.follower_id' clashes with reverse accessor for 'UserFollower.user_id'.

HINT: Add or change a related_name argument to the definition for 'UserFollower.follower_id' or 'UserFollower.user_id'.
AppName.UserFollower.user_id: (fields.E304) Reverse accessor for 'UserFollower.user_id' clashes with reverse accessor for 'UserFollower.follower_id'.
HINT: Add or change a related_name argument to the definition for 'UserFollower.user_id' or 'UserFollower.follower_id'.

My question here would be, why exactly is this wrong? And how do I fix this?

You need to add related_name

class UserFollower(models.Model):
    user_id = models.ForeignKey(User,related_name="users")
    follower_id = models.ForeignKey(User,related_name="followers")

Why this

"If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased."

But if you have more than one foreign key in a model, django is unable to generate unique names for foreign-key manager. You can help out by adding "related_name" arguments to the foreignkey field definitions in your models.

So, you can read more here in django docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM