【Django】模型层开发之重写模型类
在Django模型层开发中,我们可能会碰到这样的场景:django内置的数据表已经包含了用户数据表,但是其中并不包含我们想要的数据项,那么这时候有两种选择,要么重写用户信息模型类要么重新编写一个新的用户信息模型类,若选择重新编写,那么在数据库中将出现两个用户信息类,信息冗余且浪费资源。
Django内置的用户模型类源码如下所示:
class AbstractUser(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
Username and password are required. Other fields are optional.
"""
username_validator = UnicodeUsernameValidator()
username = models.CharField(
_('username'),
max_length=150,
unique=True,
help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[username_validator],
error_messages={
'unique': _("A user with that username already exists."),
},
)
first_name = models.CharField(_('first name'), max_length=150, blank=True)
last_name = models.CharField(_('last name'), max_length=150, blank=True)
email = models.EmailField(_('email address'), blank=True)
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:
......
可以清晰地看到不包含我们实际开发中需要的用户昵称
、性别
等数据项,因此我们继承于该类,向其中添加我们所需要的数据列:
- 重写USER模型类
由于是重写用户数据类因此要继承于AbstractUser类,而不是models.Model类。
# models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
GENDER_CHOICES = (
("male", "男"),
("famale", "女")
)
class UserProfile(AbstractUser):
"""
重写用户模型类,继承自 AbstractUser
"""
nick_name = models.CharField(max_length=50, verbose_name="昵称", default="")
birthday = models.DateField(verbose_name="生日", null=True, blank=True)
gender = models.CharField(verbose_name="性别", choices=GENDER_CHOICES, max_length=6)
address = models.CharField(max_length=100, verbose_name="地址", default="")
mobile = models.CharField(max_length=11, unique=True, verbose_name="电话号码")
image = models.ImageField(upload_to="head_image/%Y%m", default="default.jpg")
class Meta:
"""
对当前表进行相关设置
"""
verbose_name = "用户信息"
verbose_name_plural = verbose_name
def __str__(self):
"""返回一个对象的描述信息"""
if self.nick_name:
return self.nick_name
else:
return self.username
- 在setting.py文件中设置重写的用户模型类位置
AUTH_USER_MODEL
参数格式为:app名.类名,而不是模块名.类名或包名.模块名.类名。
AUTH_USER_MODEL = "user.UserProfile"