为什么我不应该直接将其他配置文件字段添加到我的 django.contrib.auth.models.User 表中?
要在 Django 中添加其他用户配置文件信息,似乎建议使用 AUTH_PROFILE_MODEL 。
但是,直接向 django.contrib.auth.models.User 表添加额外的配置文件字段有什么缺点吗?对我来说,这似乎更容易/直接(尽管我承认,我还没有掌握如何使用信号)。
是否有任何非常强烈的实际理由反对这样做?
To add additional user profile information in Django, it seems that using AUTH_PROFILE_MODEL
is the suggested way to go.
However, are there any disadvantages of adding additional profile fields directly to the django.contrib.auth.models.User
table? To me, this seems to be much easier/straightforward (though granted, I don't yet have a grasp on using signals).
Are there any very strong practical reasons against doing it this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以想到以下原因:
Django 更新
每次更新 Django 时,你都必须更新你的
contrib.auth
这样你就不会破坏你的应用程序,这是一个维护恶梦。使用 AUTH_PROFILE_MODEL 方法使 Django 更新变得轻松,同时它提供了向用户添加新信息的能力。我相信这被称为松散耦合。User
依赖应用程序如果您向
User 添加字段,则严重依赖具有完全相同字段的
模型被声明为User
的第 3 方应用程序将会失败NOT NULL
或删除一些预期存在的模型。进一步阅读
AUTH_PROFILE_MODEL
:I can think of following reasons:
Django updates
You have to update your
contrib.auth
each time you update Django so you don't break your application, and this is a maintenance nightmare. UsingAUTH_PROFILE_MODEL
method makes Django updates painless while it provides ability to add new information toUser
. This is called loose coupling i belive.User
dependant applications3rd party application that heavily rely on
User
having the exact same fields will fail if you for example add fields toUser
model that are declared asNOT NULL
or remove some that are expected to be there.Further reading about
AUTH_PROFILE_MODEL
:简而言之,使用配置文件更易于维护。根据我的理解,建议不要进行更改,一旦更新 Django 版本,这些更改就会被删除。如果您修改 django.contrib.auth.models.User 模型,则更新后更改将被删除,或者您将负责合并所做的任何更改(如果有)。另一方面,如果代码像配置文件一样存在于您的应用程序中,那么管理起来会更容易。基于此,如果您找到另一种方法可以实现相同的效果,或者如果您不认为它是维护麻烦,那么无论哪种方式都应该不重要。
Short answer, it is more maintainable to use profiles. Based on my understanding what is advised against is making changes that will be removed once you update your Django version. If you modify
django.contrib.auth.models.User
model, then the changes will be removed once you update, or you will be responsibly for merging any changes done if any. On the other hand if the code lives in your application such as the profiles does then it's easier to manage. Based on that if you find another method that achieves the same, or if you don't see it as a maintenance hassle then It should not matter much one way or the other.