Skip to main content
 首页 » 编程设计

python之Django 用户模型字段保存在哪里

2024年10月01日35pengyingh

抱歉,如果这是一个非常基本的问题,但我想知道像 is_active 这样的 Django 用户模型字段值保存在哪里,因为我没有在数据库中看到它们。

我正在使用自定义用户模型,但它们仍必须保存在某处...:)

模型.py

class MyUserManager(BaseUserManager): 
    def create_user(self, username, email, password=None): 
        """ 
        Creates and saves a User with the given email and password. 
        """ 
        if not email: 
            raise ValueError('Users must have an email address') 
 
        user = self.model( 
            email=self.normalize_email(email), 
        ) 
 
        self.username = username 
        user.set_password(password) 
        user.save(using=self._db) 
        return user 
 
    ... 
 
class MyUser(AbstractBaseUser): 
    email = models.EmailField( 
        verbose_name='email address', 
        max_length=255, 
        unique=True, 
    ) 
 
    is_active = False 
 
    objects = MyUserManager() 
 
    USERNAME_FIELD = 'email' 
 
    ... 

数据库中的表:

 Schema |          Name          | Type  |   Owner     
--------+------------------------+-------+------------ 
 public | auth_group             | table | xxx 
 public | auth_group_permissions | table | xxx 
 public | auth_permission        | table | xxx 
 public | django_admin_log       | table | xxx 
 public | django_content_type    | table | xxx 
 public | django_migrations      | table | xxx 
 public | django_session         | table | xxx 
 public | drillapp_myuser        | table | xxx 
 public | drillapp_question      | table | xxx 
 public | drillapp_story         | table | xxx 
(10 rows) 

这是用户表的样子。没有 is_active 列。

drill=# select * from drillapp_myuser; 
 id |               password                | last_login |        email          
----+---------------------------------------+------------+---------------------- 
 45 | pbkdf2_sha256$36000$GNzjZ...edPewC28= |            | xxx0@xxx.com 
(1 row) 

在 shell 中,我可以访问 is_active 字段,我在数据库中看不到它:

>>> from django.contrib.auth import get_user_model 
>>> u = get_user_model().objects.get(pk=45) 
>>> u.is_active 
False 

请您参考如下方法:

在你的例子中,is_active 是没有保存在数据库中的 python 类 property,如果你想保存和操作它,你应该使用 models.BooleanField