AbstractUser和AbstractBaseUser看起来十分类似,若是你不熟悉djiango的auth重写User,那你很容易弄错,致使一堆bug。python
咱们查看AbstractUser的源码得知,AbstractUser继承了AbstractBaseUser,讲得俗气一点就是,AbstractBaseUser是AbstractUser的爸爸。数据库
咱们能够猜测一下,既然两者是继承与被继承关系,那么AbstractUser是否是在AbstractBaseUser的基础上功能更加完善呢?AbstractBaseUser是否是更加open呢?django
经过官方文档咱们能够获得答案:app
AbstractUserui
The documentation explains this fully. AbstractUser is a full User model, complete with fields, as an abstract class so that you can inherit from it and add your own profile fields and methods. AbstractBaseUser only contains the authentication functionality, but no actual fields: you have to supply them when you subclass.this
文档充分解释了这一点。 AbstractUser是一个完整的用户模型,包含字段,做为一个抽象类,以便您能够继承它并添加您本身的配置文件字段和方法。 AbstractBaseUser仅包含身份验证功能,但不包含实际字段:当您继承子类时,您必须提供它们。spa
The AbstractUser is basically just the "User" class you're probably already used to. AbstractBaseUser makes fewer assumptions and you have to tell it what field represents the username, what fields are required, and how to manage those users.命令行
AbstractUser基本上就是您可能已经习惯的“用户”类。 AbstractBaseUser的继承较少,您必须告诉它哪一个字段表明用户名,须要哪些字段以及如何管理这些用户。code
AbstractBaseUser blog
If you're just adding things to the existing user (i.e. profile data with extra fields), then use AbstractUser because it's simpler and easier. If you want to rethink some of Django's assumptions about authentication, then AbstractBaseUser gives you the power to do so.
若是您只是将事情添加到现有用户(即具备额外字段的配置文件数据),则使用AbstractUser是由于它更简单,更简单。 若是您想从新考虑一下Django关于认证的假设,那么AbstractBaseUser会为您提供这样的权力。
什么意思呢?就是说啊,咱们习惯的继承 的AbstractUser 类是高度集成的,里面给你定义了一堆的字段,不须要你人为去定义了。
上面是咱们须要额外添加的,下面是django帮你作的(没有显示彻底,右边还有本身添加的部分字段)
但回过头来想,高度集成的东西每每扩展性和兼容性就较差,万一哪天一个项目来了说我只须要基本的用户名密码,用户类型等等三四个字段,其余的都不care,那么很显然这时候用AbstractUser 是不合理的,将形成数据库资源的浪费,下降数据库效率。
这时候咱们就能够来继承AbstractBaseUser 类来自定义一些字段。下面咱们来看看AbstractBaseUser 的用法
model
建立后的全部表字段
因而可知,django只帮咱们建立了id、password、last_login这三个字段。
在模型类中咱们必须定义一个用户名字段,并指定属性为unique,而后告诉django这个字段是用户名字段:
username = models.CharField(max_length=32,unique=True) USERNAME_FIELD = 'username' # 这当中的username你能够任意命名,unique必须指定为True
若是不写这两句话,你会发现执行数据库迁移命令怎么建立表都没办法建立出来,一直报错:
AttributeError: type object 'UserInfo' has no attribute 'USERNAME_FIELD'
若是你要删库从新建model,请到你的app下面的migrations文件夹下面把除__init__.py的其余文件所有删除,再执行数据库迁移命令。
顺带把数据库迁移命令语句丢在这儿:
第一种方式:PyCharm的Terminal命令行:
第一条:python manage.py makemigrations 或者 python3 manage.py makemigrations ###根据你配置的python环境而定 第二条:python manage.py migrate 或者 python3 manage.py migrate
第二种方式:PyCharm上菜单栏Tools --> run manage.py Task...
第一条:makemigrations
第二条:migrate
以为写得好,给个赞呗~~~~~~欢迎来搂~~