self.model() 在 django 自定义 UserManager 中

self.model() in django custom UserManager

所以,我是 Django 的新手。尽管事实上我的代码在遵循 Django 文档 'Customizing authentication in Django' 之后工作,但我不明白他们示例中的 self.model(...) 是如何工作的,它来自哪里以及它如何与'self'.

这是在文档底部找到的示例。

from django.db import models

from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

class MyUserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

   ->   user = self.model(
            email=self.normalize_email(email),
            date_of_birth=date_of_birth,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user
...

嗯,你这里定义的是一个MyUserManagerclass。这继承自 BaseUserManager class [GitHub]. This is a subclass of the Manager class [GitHub]。您实际上一直在使用经理。例如 SomeModel.objects 是经理。

如果使用管理器,则它会引用其管理的 模型。所以 SomeModel.objects 是一个经理,但是那个经理有一个属性 .model 实际上指回 SomeModel class.

现在 Python 中的 class 通常 可调用 。例如,如果调用 int('42'),则调用 int(..) 构造函数 。在这种情况下,您的 self.model 将 - 默认情况下 - 由 User 模型(尽管可以被覆盖)。

现在在 Django 中,模型的构造函数采用命名参数来构造模型实例。如果你写 User(date_of_birth=date(2018, 7, 3), email='bob@work.com'),那么你构建了一个 unsaved User 实例,字段值为 July 3rd 2018 作为 date_of_birth,并且 'bob@work.com'作为 email.

所以在这里你通常构造一个 User 实例(或者你用来表示 Users 的另一个模型的实例)。然后您稍后使用 user.save() 将该实例保存到数据库,并 return 它。