当模型具有同一模型的 2 个外键时,管理内联?

发布于 2024-11-02 08:44:46 字数 378 浏览 10 评论 0原文

我在我的网站上创建了一个推荐系统。诚然,现在已经晚了,这可能不是正确的关系类型。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑饮青盏花 2024-11-09 08:44:46

实际上,这是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文