在Djang中添加来自同一模型的两个ForeignKey字段

2024-05-10 01:15:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在Django中创建一个用户和追随者关系,如下所示

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

为此,我做了以下工作:

^{pr2}$

其中Userdjango.contrib.auth.models.User模型。在运行makemigrations时,我得到以下错误:

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

我的问题是,为什么这是错误的?我该怎么解决这个问题?在


Tags: oridfieldsfor错误withreverseuser
1条回答
网友
1楼 · 发布于 2024-05-10 01:15:28

您需要添加related_name

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

为什么这样

"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.

所以,你可以在django docs阅读更多

相关问题 更多 >