User manager methods create() and create_user()

前端 未结 2 409
猫巷女王i
猫巷女王i 2020-12-16 01:05

I have encountered with some suspicious behavior of create() method of User object manager. Looks like password field isn\'t required

2条回答
  •  一向
    一向 (楼主)
    2020-12-16 02:01

    That's exactly why the user model has a custom manager with a UserManager.create_user() method for creating users. There are two problems with using the QuerySet.create() method on User instances:

    1. If you run the management command python manage.py sql, pay attention to the auth_user schema:

      CREATE TABLE "auth_user" (
          ...
          "password" varchar(128) NOT NULL,
          ...
      )
      

      In SQL, an empty string, '', does not equate to NULL, i.e. ISNULL('') != TRUE.

    2. QuerySet.create() and QuerySet.update() do not trigger model validation. Model validation only happens when ModelForm instances call the Model.full_clean() instance method.

      Raising a validation error in the context of working with the QuerySet API directly simply makes no sense in Django. That's why you can do something like User.objects.create(username='foo', password='') even though CharField().validate(value='', None) would raise a ValidationError for a blank string.

    For the reasons above, you should defer from using User.objects.create() and rely on the supplied User.objects.create_user() method from the model's custom manager.

提交回复
热议问题