Django:扩展用户模型与创建用户配置文件模型

Django: extending user model vs creating user profile model

我正在 Django 中创建一个应用程序,到目前为止我一直在使用像这样的扩展用户模型:

class MyUser(AbstractBaseUser):
...

所有用户和配置文件信息,但我看到很多人使用 OneToOneField 为配置文件和用户本身创建不同的模型,使用 OneToOneField,尽管这些大多是老问题。 我的问题是:哪个更好,如果没有最好的,每个解决方案的优势是什么? 谢谢!

ForeignKey是建立一对多的关系。换句话说,它将 return 一个查询集。例如,一辆汽车有很多轮子,但一个轮子没有连接到几辆不同的汽车上。

OneToOneField 将在严格的两个对象之间创建关系。例如,轮辋属于左前轮胎,只有那个轮胎才有那个轮辋。

这有意义吗?

这取决于你想做什么——如果你对最新版本的 Django 中的用户模型感到满意,你应该直接使用它——它很简单,而且你会获得很多功能随之而来的——例如一个非常好的许可系统,你可以确保与所有第三方模块兼容。但是,如果您认为需要扩展 User 模型,那么操作起来非常简单。您可能会发现,将来您需要向模型中添加比预期更多的方法。

您在单独的 UserProfile / User 模型中看到的示例主要是 django < 1.5 的遗留问题,这是扩展 User 模型的推荐方法。没有理由再遵循这种模式——在你只想要一个模型的情况下必须使用两个模型需要做更多的工作


2019年更新

如果您开始一个新的 Django 项目,您应该始终根据 Django 文档创建您自己的继承自 AbstractUser 的自定义用户模型,即

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass 

即使您不需要任何附加功能。这样做的原因是,只需很少的努力,您就可以轻松地在未来自定义您的用户对象。在完成 运行 初始迁移后,将内置 User 对象替换为您自己的对象非常费力,除非您能够删除所有数据和迁移并重新开始。

我在 Django 文档中找到了一些有用的信息:

Extending Django’s default User¶

If you’re entirely happy with Django’s User model and you just want to add some additional profile information, you could simply subclass django.contrib.auth.models.AbstractUser and add your custom profile fields, although we’d recommend a separate model as described in the “Model design considerations” note of Specifying a custom User model. AbstractUser provides the full implementation of the default User as an abstract model.

并且:

Model design considerations

Think carefully before handling information not directly related to authentication in your custom User Model.

It may be better to store app-specific user information in a model that has a relation with the User model. That allows each app to specify its own user data requirements without risking conflicts with other apps. On the other hand, queries to retrieve this related information will involve a database join, which may have an effect on performance.

所以如果我没看错的话,就是说如果字段是和认证相关的,那么你应该考虑替换原来的User模型。但如果它不相关,例如个人资料字段、生日或 profile_image,那么您可能想要创建一个引用原始用户模型的独立应用程序。

我找到了一个很好的教程:http://riceball.com/d/content/django-18-tutoria-52-adding-user-profile