The system I work on has People who may or may not be Users, and very infrequently Users who may not be a Person. In fact, an extension to the system has meant that there will be more of these: a User who needs to be able to generate reports (say, a Franchisor who needs to only be able to access aggregate data from franchises, that might belong to multiple companies) who is never rostered on for shifts, which is what the Person class is all about.
Anyway, the long and the short of this was that I thought it might be a good idea to look at sub-classing User for ManagementUser.
I guess I should have listened to those smarter than me who shouted that sub-classing User is not cool. Although they never gave any concrete reasons, but now I have one.
You cannot easily convert a superclass object to a specialised sub-class. Once a user is a User, it’s hard to make them into a ManagementUser.
It can be done: the following code will take a User (or any parent class) object, a User (or whatever) subclass, and any other keyword arguments that should be passed into the constructor. It saves the newly upgraded object, and returns it.
1 def create_subclass(SubClass, old_instance, **kwargs): 2 new_instance = SubClass() 3 for field in old_instance._meta.local_fields: 4 setattr(new_instance, field.name, getattr(old_instance, field.name)) 5 new_instance.save() 6 return new_instance()
However, it really should check that there isn’t an existing instance, and maybe some other checks.
What advantages does sub-classing have?
The biggest advantage, or so I thought, was to have it so you can automatically downcast your models on user login, and then get access to the extended user details. For instance, if your authentication backend automatically converts User to Person, then you can get access to the Person’s attributes (like the company they work for, their shifts, etc) without an extra level of attribute access:
1 # request.user is always an auth.User instance: 2 request.user.person.company 3 # request.user might be a person, etc. 4 request.user.company
But it turns out that even this is bad. Now, in guard decorators on view functions, you cannot just test the value of an attribute, as not all users will have that attribute. Instead, you need to test to see if the attribute exists, and then test the attribute itself.
So, what do you do instead?
The preferred method in django for extending User is to use a UserProfile class. This is just a model that has a OneToOneField linked back to User. I would look at doing a very small amount of duck-punching just to make getting a hold of the profile class:
1 import logging 2 from django.contrib.auth.models import User 3 from django.db import models 4 5 class Person(models.Model): 6 user = models.OneToOneField(User, related_name="_person") 7 date_of_birth = models.DateField(null=True, blank=True) 8 9 def get_person(user): 10 try: 11 return user._person 12 except Person.DoesNotExist: 13 pass 14 15 def set_person(user, person): 16 user._person = person 17 18 if hasattr(User, 'person'): 19 logging.error('Model User already has an attribute "person".') 20 else: 21 User.person = property(get_person, set_person)
By having the person’s related name attribute as _person, we can wrap read access to it in an exception handler, and then use a view decorator like:
1 @user_passes_test(lambda u:u.person) 2 def person_only_view(request, **kwargs): 3 pass
We know this view will only be available to logged in users who have a related Person object.
I will point out that I am duck-punching/monkey-patching here. However, I feel that this particular method of doing it is relatively safe. I check before adding the property, and in reality I probably would raise an exception rather than just log an error.