Django:扩展User时,最好使用OneToOneField(User)或ForeignKey(User,unique = True)? [英] Django: When extending User, better to use OneToOneField(User) or ForeignKey(User, unique=True)?
问题描述
在通过扩展Django用户模型创建UserProfile模型时,我发现是否使用OneToOneField(User)或ForeignKey(User,unique = True)的冲突信息。
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 Doc 指定了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:
- Extending the User Model
- User Registration
在前一篇文章中,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
和 UserProfile $ c $中的字段C>。这可以用一个<àcode> 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:扩展User时,最好使用OneToOneField(User)或ForeignKey(User,unique = True)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!