如何在Django中为庞大的自定义用户(AbstractBaseUser)创建UserManager?

时间:2019-02-26 18:06:23

标签: django

这是我的django项目的自定义用户模型。

class User(AbstractBaseUser, PermissionsMixin):
phone = models.CharField(
    max_length=15,
    unique=True,
)
sms = models.BooleanField(default=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
tutor = models.ForeignKey(
    'self',
    on_delete=models.SET_NULL,
    blank=True,
    null=True,
)
TRAINING_ONLINE = 'ON'
TRAINING_DISTANCE = 'DT'
TRAINING_FULLTIME = 'FT'
TRAINING_NONE = 'NN'
TRAINING_CHOICES = (
    (TRAINING_ONLINE, 'Online'),
    (TRAINING_DISTANCE, 'Distance'),
    (TRAINING_FULLTIME, 'Fulltime'),
    (TRAINING_NONE, 'None'),
)
training = models.CharField(
    max_length=2,
    choices=TRAINING_CHOICES,
    default=TRAINING_NONE,
)
first_name = models.CharField(
    max_length=50,
    blank=True,
    null=True,
)
last_name = models.CharField(
    max_length=50,
    blank=True,
    null=True,
)
country = models.CharField(
    max_length=50,
    blank=True,
)
city = models.CharField(
    max_length=50,
    blank=True,
)
EFFICIENCY_VERY_LOW = '1'
EFFICIENCY_LOW = '2'
EFFICIENCY_MEDIUM = '3'
EFFICIENCY_HIGH = '4'
EFFICIENCY_VERY_HIGH = '5'
EFFICIENCY_CHOICES = (
    (EFFICIENCY_VERY_LOW, 'Very low'),
    (EFFICIENCY_LOW, 'Low'),
    (EFFICIENCY_MEDIUM, 'Medium'),
    (EFFICIENCY_HIGH, 'High'),
    (EFFICIENCY_VERY_HIGH, 'Very high'),
)
efficiency = models.CharField(
    max_length=1,
    choices=EFFICIENCY_CHOICES,
    default=EFFICIENCY_MEDIUM,
)
USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = []

def __str__(self):
    return self.phone

def get_full_name(self):
    return self.first_name + ' ' + self.last_name

def get_short_name(self):
    return self.first_name

@property
def is_staff(self):
    return self.staff

@property
def is_admin(self):
    return self.admin

@property
def is_active(self):
    return self.active

我看过一些带有** extra_fields的教程,但是我真的不知道如何正确使用它来减少不必要的代码。

我不知道如何正确为其编写自定义UserManager。我应该设置默认值还是已经由模块完成?你能帮我吗?


我需要通过电话号码和密码进行身份验证。我还需要在数据库中存储一些有关用户的其他信息(他们的名字和姓氏等等)。不必要的代码是这样的:

def create_user(self, phone=None, first_name=None, password=None, sms=True, active=True, staff=False, admin=False, tutor=None, training='NN', efficiency='3', last_name=None, country=None, city=None):

我想通过使用AbstractBaseUser重新定义(不扩展!)标准Django用户模型

1 个答案:

答案 0 :(得分:0)

类UserOtherInfo(models.Model):

'''
To extend basic user model (for users extra informations)
'''
user            = models.OneToOneField(User , on_delete=models.CASCADE)
phone           = models.CharField('Phone Number', max_length=15,null=True,blank=True)

''' 在这里您可以根据需要添加任意多个字段 '''