User.objects.create_user() 与 User.objects.create() 与 User().save() 在 django 之间的区别

Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django

在 Django 文档中,它使用 User.objects.create_user() 创建用户。我很困惑,这与 User.objects.create()User().save() 之间有什么区别,后者是创建其他模型对象的正常方法

最显着的区别是,如果您向 .create() 方法提供密码,它将逐字设置在用户身上,并且不能用于验证用户。

>>> user = User.objects.create(username="foo", password="bar")
>>> user.password
'bar'
>>> user.check_password("bar")
False

相反,create_user() 方法对密码参数进行哈希处理,然后是。

>>> user = User.objects.create_user(username="foo", password="bar")
>>> user.password
'pbkdf2_sha2560000pHBVu3tYYbK$ESG1nbUY2ZhEmstJ7Fzu1DioXmGYXiLw31YDkOGn9E0='
>>> user.check_password("bar")
True

https://github.com/django/django/blob/master/django/contrib/auth/models.py#L145

其他一些'tidying'也完成了。请参阅上面链接的函数的其余部分。

User.objects.create_user() 是一个辅助函数,它提供有用的实用程序来创建一个用户,否则您将不得不自己做。根据文档:

Creates, saves and returns a User

The username and password are set as given. The domain portion of email is automatically converted to lowercase, and the returned User object will have is_active set to True.

If no password is provided, set_unusable_password() will be called.

The extra_fields keyword arguments are passed through to the User’s __init__ method to allow setting arbitrary fields on a custom user model.

如果没有 create_user(),您可以使用您提到的方法自己创建功能,但它提供了有用的处理和实用程序。

create()save() 是创建模型实例的通用方法。他们不做任何特定于用户模型的事情,而 create_user() 方法是创建用户的特定方法。

在使用通用方法创建用户时,您设置为密码的值不会hashed.You需要自己这样做。

u = User(username="username")
u.set_password("password")
u.save()

此外,如果没有额外的数据库查询,您不能使用 create() 方法执行相同的操作。

使用 create_user() 时,用户名和密码设置为给定,密码将自动散列,返回的用户对象将 is_active 设置为 True

你应该得到用户模型:

from django.contrib.auth import get_user_model
UserModel = get_user_model()
user = UserModel.objects.create(username="Mr Foo", password="bar")
user.save()

或者:

user = UserModel.objects.create_user("Mr Foo", password="bar")
user.save()

如果您使用 create_user(),则无需使用 save() 保存。 create_user() 已经将用户保存到数据库中见:https://docs.djangoproject.com/en/4.0/topics/auth/default/