Django:扩展用户模型与创建用户配置文件模型 [英] Django: extending user model vs creating user profile model

查看:97
本文介绍了Django:扩展用户模型与创建用户配置文件模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class MyUser(AbstractBaseUser):
...

,其中包含所有用户和个人资料信息,但是我看到很多人使用 OneToOneField 为配置文件和用户本身在堆栈溢出时创建不同的模型,尽管这些大多数都是旧问题。
我的问题是:哪种更好,如果没有最好的解决方案,每种解决方案都有哪些优势?
谢谢!

解决方案

这取决于您要执行的操作-如果您对用户模型感到满意因为它代表了最新版本的Django,所以您应该只使用它-这很容易,并且会附带很多功能-例如,一个非常好的权限系统,并且您可以肯定与它兼容所有第三方模块。但是,如果您需要扩展用户模型,那么操作非常简单。您可能会发现,将来您需要向模型中添加比预期更多的方法。



使用单独的UserProfile / User模型看到的示例大部分都是旧的django的< 1.5,这是扩展用户模型的推荐方法。没有理由再遵循这种模式了-必须使用两种模型,而您只需要一种模型



2019 Update p>

如果要启动新的Django项目,则应始终创建自己的自定义用户模型,该模型继承自 AbstractUser ,例如根据Django文档,即

 从django.contrib.auth.models import AbstractUser 

类User (AbstractUser):
通过

即使您不需要任何其他功能。这样做的原因是,您只需花费很少的精力,将来就可以轻松自定义用户对象。在运行初始迁移后,用内置的 User 对象替换掉自己的内建对象非常费力,除非您能够删除所有数据和迁移并开始结束。


I'm creating an app in Django and so far I have been using an extended user model like so:

class MyUser(AbstractBaseUser):
...

with all the user and profile info, but I see a lot of people creating different models for the profile and the user itself on stack overflow, using OneToOneField, although those are mostly old questions. My question is: which is better and, if there isn't a best among them, what are the advantages for each solution? thanks!

解决方案

It depends on what you want to do -- if you're happy with the User model as it stands in the latest version of Django you should just use that -- it's easy and you'll get a lot functionality that goes along with it -- for example a pretty good permission system, and you can be sure to be compatible with all third party modules. But if you thing you'll need to expand on the User model, it's pretty straightforward how to do it. You might find that in the future you need to add more methods to your model than you expected.

The examples that you see with separate UserProfile / User model are mostly a legacy of django < 1.5, where that was the recommended way to extend the User model. There's no reason to follow that pattern any more -- it's a lot more work to have to use two models where you just want one model


2019 Update

If you are starting a new Django project, you should always create your own custom user model that inherits from AbstractUser, as per the Django documentation, i.e.

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass 

even if you don't need any additional functionality. The reason for this is that for very low effort, you are making it easy to customize your user object in the future. It's very laborious to replace the built-in User object with your own after you have run the initial migrations, unless you're able to delete all of your data and migrations and start over.

这篇关于Django:扩展用户模型与创建用户配置文件模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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