Django:扩展用户时,最好使用 OneToOneField(User) 还是 ForeignKey(User, unique=True)? [英] Django: When extending User, better to use OneToOneField(User) or ForeignKey(User, unique=True)?

查看:28
本文介绍了Django:扩展用户时,最好使用 OneToOneField(User) 还是 ForeignKey(User, unique=True)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现在创建 UserProfile 时是否使用 OneToOneField(User)ForeignKey(User, unique=True) 的信息存在冲突> 通过扩展 Django 用户模型来构建模型.

I'm finding conflicting information on whether to use OneToOneField(User) or ForeignKey(User, unique=True) when creating a UserProfile model by extending the Django User model.

使用这个更好吗?:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)

还是这个?:

class UserProfile(models.Model):
    user = models.OneToOneField(User)

Django 文档 指定 OneToOneField,而 Django Book 示例 使用 ForeignKey.

The Django Doc specifies OneToOneField, while the Django Book example uses ForeignKey.

James Bennett 也有两篇博客文章也提供了相互矛盾的例子:

James Bennett also has two Blog posts that providing conflicting examples as well:

在前一篇博文中,Bennett 提供了一些他改用 ForeignKey 而不是 OneToOneField 的原因,但我不太明白,尤其是当我看到其他推荐相反的帖子.

In the former post, Bennett provides some reasons why he switched to using ForeignKey instead of OneToOneField, but I don't quite get it, especially when I see other posts that recommend the opposite.

我很想知道您的偏好以及原因.或者,这甚至重要吗?

I'm curious to know your preference and why. Or, does it even matter?

推荐答案

文章中给出的唯一真正原因是它可以设置为 User 的管理页面将同时显示UserUserProfile 中的字段.这可以用 OneToOneField 复制,并带有一点肘部润滑脂,所以除非你沉迷于在管理页面中显示它而不用牺牲一点清晰度(我们可以创建多个每个用户的个人资料?!哦,不,等等,它是唯一的.")我会使用 OneToOneField.

The only real reason given in the article is that it can be set up so that the admin page for User will show both the fields in User and UserProfile. This can be replicated with a OneToOneField with a little elbow grease, so unless you're addicted to showing it in the admin page with no work at the cost of a bit of clarity ("We can create multiple profiles per user?! Oh no, wait, it's set unique.") I'd use OneToOneField.

这篇关于Django:扩展用户时,最好使用 OneToOneField(User) 还是 ForeignKey(User, unique=True)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆