Django中create()方法和create_user()方法的区别

sy5wg1nm  于 2022-12-01  发布在  Go
关注(0)|答案(1)|浏览(137)

用户模型是我自己创建的,我没有使用Django的默认模型。要创建一个用户,如果我使用create()方法,日期字段将设置该字段的值,但如果我使用create_user()方法,我必须给日期字段一个值。为什么会发生这种情况?

class UserManager(BaseUserManager):
    def create_user(self, email, f_name, l_name, phone, create, password):
        user = self.model(email=self.normalize_email(email), f_name=f_name, l_name=l_name, phone=phone,
                          create=create, )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, f_name, l_name, phone, create, password):
        user = self.create_user(email, f_name, l_name, phone, create, password)
        user.is_admin = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

    class User(AbstractBaseUser):
        f_name = models.CharField(max_length=50)
        l_name = models.CharField(max_length=50, blank=True, null=True, )
        email = models.EmailField(unique=True, blank=True, null=True)
        phone = models.BigIntegerField(blank=True, null=True, )
        data = models.DateTimeField(auto_now_add=True)
        is_active = models.BooleanField(default=True)
        is_admin = models.BooleanField(default=False)
        is_superuser = models.BooleanField(default=False)
        permission = models.ManyToManyField(Permission, related_name='users')
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = ['phone', 'f_name', 'l_name', 'create']
        objects = UserManager()
fnvucqvd

fnvucqvd1#

您自己的create_user()方法不接收和处理extra_fields。extra_fields是未指定的参数。在您的示例中,email、f_name、l_name、phone、create、password被指定,而其他参数是extra_fields。
在django.contrib.auth.模型中的create_user()和_create_user()方法处理
额外字段的方式如下。

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, username, email, password, **extra_fields):
        """
        Create and save a user with the given username, email, and password.
        """
        if not username:
            raise ValueError("The given username must be set")
        email = self.normalize_email(email)
        # Lookup the real model class from the global app registry so this
        # manager method can be used in migrations. This is fine because
        # managers are by definition working on the real model.
        GlobalUserModel = apps.get_model(
            self.model._meta.app_label, self.model._meta.object_name
        )
        username = GlobalUserModel.normalize_username(username)
        user = self.model(username=username, email=email, **extra_fields)
        user.password = make_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, username, email=None, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", False)
        extra_fields.setdefault("is_superuser", False)
        return self._create_user(username, email, password, **extra_fields)

在django.db.models.query中定义create()方法也可以像这样使用**kwargs来接收和处理指定的和未指定的参数。

def create(self, **kwargs):
    """
    Create a new object with the given kwargs, saving it to the database
    and returning the created object.
    """
    obj = self.model(**kwargs)
    self._for_write = True
    obj.save(force_insert=True, using=self.db)
    return obj

因此如果在create_user()方法中添加**extra_fields,则日期将自动分配。

class UserManager(BaseUserManager):
    def create_user(self, email, f_name, l_name, phone, create, password, **extra_fields):
        user = self.model(email=self.normalize_email(email), f_name=f_name, l_name=l_name, phone=phone,
                          create=create, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

相关问题