"添加到auth_user"
"添加到auth_user"
这个问题在这里已经有答案了:
我有一个程序,它从django数据库的auth_user表获取大部分数据。我不知道如何添加一个新列并使其实际工作,因为它在我这样做时无法识别它。有人知道如何向默认的django数据库的auth_user表添加可以使用的列吗?
admin 更改状态以发布 2023年5月20日
您可以覆盖默认用户模型或使用OneToOneField关系扩展用户模型以满足此要求。
1. 我将向您展示如何进行自定义用户模型。
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from core.util.validators import UnicodeUsernameValidator from .manager import UserManager class User(AbstractBaseUser, PermissionsMixin): """ Username, Email and password are required. Other fields are optional. """ username_validator = UnicodeUsernameValidator() username = models.CharField( _('username'), max_length=150, unique=True, help_text=_( '150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, null=True, default=None ) email = models.EmailField( _('email address'), blank=False, unique=True, error_messages={ 'unique': _("A user with that email address already exists."), }, ) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = UserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') permissions = ( ('user_permission', "User Permission"), ('admin_permission', "Admin Permission"), )
这类似于User模型中所拥有的内容的副本。在此处,您可以添加新字段。
请确保在settings.py中注册此字段。
AUTH_USER_MODEL = 'userapp.User'
您可以访问extra_fields,例如:
user.extra_field
2. 我将向您展示如何使用OneToOneField进行扩展。
from django.contrib.auth import get_user_model class Profile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) ... # Extra fields Here
然后,您可以像下面这样访问额外的字段:
user.profile.extra_field