[Fixed]-Self.model() in django custom UserManager

27👍

Well, what you define here is a MyUserManager class. This inherits from the BaseUserManager class [GitHub]. This is a subclass of the Manager class [GitHub]. You actually use manager all the time. For example SomeModel.objects is a manager.

A manager has, if it is used, a reference to the model it manages. So SomeModel.objects is a manager, but that manager has an attribute .model that actually refers back to the SomeModel class.

Now a class in Python is typically callable. If you for example call int('42'), you call the int(..) constructor. In this case your self.model will – by default – by the User model (although that can be overwritten).

Now in Django the constructor of a model takes, named parameters, to construct a model instance. If you write User(date_of_birth=date(2018, 7, 3), email='bob@work.com'), then you construct an unsaved User instance with as field values July 3rd 2018 as date_of_birth, and 'bob@work.com' as email.

So here you typically construct a User instance (or an instance of another model you used to represent Users). You then later use user.save() to save that instance to the database, and return it.

Leave a comment