当模型具有同一模型的 2 个外键时,管理内联?
我在我的网站上创建了一个推荐系统。诚然,现在已经晚了,这可能不是正确的关系类型。
class Referral(models.Model):
referred=models.ForeignKey(User, related_name="referred")
referrer=models.ForeignKey(User,related_name="referrer")
def __unicode__(self):
return self.user.first_name
其他人会建议用什么来代表这种关系?如果这是正确的,有没有办法让我将其变成用户管理员的伪内联?当前构造是不允许的,因为同一个表有两个外键。
谢谢
I've created a referral system on my website. Admittedly, it's late and this might not be the right sort of relationship.
class Referral(models.Model):
referred=models.ForeignKey(User, related_name="referred")
referrer=models.ForeignKey(User,related_name="referrer")
def __unicode__(self):
return self.user.first_name
What would others recommend to represent this relationship? If this is about right, is there a way for me to turn this into a pseudo inline for the User Admin? It's not allowed as currently constructed because there are two foreign keys to teh same table.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,这是 User 与其自身之间的多对多关系 - Referral 类本身不会向该关系添加任何内容。
通常,您可以将 ManyToManyField 添加到模型中,它将显示在管理中 - 但我猜测您引用的 User 类是内置的 django.contrib.auth User ,您不能直接修改它。因此,一种方法是定义一个 UserProfile 类,该类具有 User 的外键,并在其中添加 ManyToMany 关系。
编辑回复评论 不,这不完全是我的意思。我是说你应该完全放弃 Referral 课程。仅由两个 FK 组成的模型(无论它们是否属于同一模型)就是 M2M 关系的直通表。在您的情况下,这种关系是在 User 和它本身之间 - 但正如我所说,因为您不想更改 User,所以它是在新的 UserProfile 模型和它本身之间。
Actually, this is a ManyToMany relationship between User and itself - the Referral class itself does not add anything to the relationship.
Normally, you can just add the ManyToManyField to the model and it will be displayed in the admin - but I'm guessing that the User class you reference is the built-in django.contrib.auth User, which you can't directly modify. So one way would be to define a UserProfile class which has a ForeignKey to User, and add the ManyToMany relationship there.
Edit in response to comment No, that's not quite what I meant. I'm saying you should drop the Referral class completely. A model which is just two FKs and nothing else - whether they're both to the same model or not - is the through table of a M2M relationship. That relationship, in your case, is between User and itself - but as I say, since you don't want to change User, it is between a new UserProfile model and itself.