是在Django中定义自己的用户模型还是使用Django auth用户模型?

2024-09-26 22:13:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我从Django应用程序模式设计开始,我的模式有UserProfile、userfavorites和UserComments模型。 在做了一点研究之后,我发现我们可以使用django自己的User模型,或者我们可以创建自己的用户模型,该模型将从AbstractUser扩展

Platform = Django 1.8.5

我发现了许多类似的问题,但现在我有了Django框架的最新版本,有什么变化吗?你知道吗

还需要知道每种方法的利弊


Tags: django方法用户模型版本框架应用程序模式
2条回答

在新项目中,强烈考虑从自定义用户模型开始。

原因是,如果您想稍后更改您的用户模型,那么有一个明确的方法可以做到这一点(迁移)。然而,当您已经与auth用户建立了ForeignKey关系(etc)时,从auth用户切换到自定义用户是一件痛苦的事(见下文)。考虑到在项目开始时使用自己的模型非常容易(可能只是复制auth模型),没有什么理由不这样做。你知道吗

文档中提到了以后更改AUTH\u USER\u模型有多难:

Warning

Changing AUTH_USER_MODEL has a big effect on your database structure. It changes the tables that are available, and it will affect the construction of foreign keys and many-to-many relationships. If you intend to set AUTH_USER_MODEL, you should set it before creating any migrations or running manage.py migrate for the first time.

Changing this setting after you have tables created is not supported by makemigrations and will result in you having to manually fix your schema, port your data from the old user table, and possibly manually reapply some migrations.

Warning

Due to limitations of Django’s dynamic dependency feature for swappable models, you must ensure that the model referenced by AUTH_USER_MODEL is created in the first migration of its app (usually called 0001_initial); otherwise, you will have dependency issues.

In addition, you may run into a CircularDependencyError when running your migrations as Django won’t be able to automatically break the dependency loop due to the dynamic dependency. If you see this error, you should break the loop by moving the models depended on by your User model into a second migration (you can try making two normal models that have a ForeignKey to each other and seeing how makemigrations resolves that circular dependency if you want to see how it’s usually done)

换句话说,如果在项目开始时选择不使用AUTH\u USER\u模型,那么以后几乎不可能进行更改。你知道吗

有一个ticket #24370用于将自定义用户模型和AUTH\u user\u model设置添加到默认项目模板,并建议在文档中这样做。这张罚单正等着有人来执行。你知道吗

从Django的文件中提取的

If you wish to store information related to User, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user

所以只需将额外的用户字段添加到UserProfile模型。与您想要的每个模型建立一对一的关系

相关问题 更多 >

    热门问题