AbstractUser和AbstractBaseUser看起來十分相似,如果你不熟悉djiango的auth重寫User,那你很容易弄錯,導致一堆bug。
我們查看AbstractUser的源碼得知,AbstractUser繼承了AbstractBaseUser,講得俗氣一點就是,AbstractBaseUser是AbstractUser的爸爸。
我們可以猜想一下,既然二者是繼承與被繼承關系,那么AbstractUser是不是在AbstractBaseUser的基礎上功能更加完善呢?AbstractBaseUser是不是更加open呢?
通過官方文檔我們可以得到答案:
AbstractUser
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.
文檔充分解釋了這一點。 AbstractUser是一個完整的用戶模型,包含字段,作為一個抽象類,以便您可以繼承它並添加您自己的配置文件字段和方法。 AbstractBaseUser僅包含身份驗證功能,但不包含實際字段:當您繼承子類時,您必須提供它們。
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的繼承較少,您必須告訴它哪個字段代表用戶名,需要哪些字段以及如何管理這些用戶。
AbstractBaseUser
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'
開放的東西往往也意味着更加純凈,那么這里就會有一些問題值得注意,當使用AbstractBaseUser 的時候我們需要注意的是:如果你使用了AbstractBaseUser ,那么django自帶的auth認證的所有用法將統統不能使用,你需要自己去寫加密、登陸判斷、存儲等等一系列方法。
如果你要刪庫重新建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
此外自定義User表,如果希望django只生成我們自己定義的User表,不生成django自帶的auth_user表,你需要導setting里加一行代碼:
AUTH_USER_MODEL = '應用名.表名'
覺得寫得好,給個贊唄~~~~~~歡迎來摟~~