1. 程式人生 > >Django使用者認證模組中繼承AbstractUser與AbstractBaseUser重寫User表的區別

Django使用者認證模組中繼承AbstractUser與AbstractBaseUser重寫User表的區別

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'

 

 

如果你要刪庫重新建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 = '應用名.表名'

 

 

 

 

 覺得寫得好,給個讚唄~~~~~~歡迎來摟~~

&n