Usually users' profiles are stored in single model. When there are multiple user types, separation is made by some field like user_type
.
Situation is a little more complicated when different data is needed for each user type.
Of course it's better when all users have same type and are granted different permissions. But since we got task to have separate user types - we'll have to solve it.
The most obvious solution is to make base profile with type identifier, which will pull needed model instance:
But I don't really like this solution. Firstly, get_final_profile
method is basically a big switch-case. Secondly - we must not forget to call extra method.
I wanted to simply write request.user.profile
ans get needed profile instance. This is possible by combining two known tricks - Upcast and AutoOneToOneField.
Allows to get sublass instance from base class instance.
Allows creating related objects on request. This field is not needed per se, only idea. Taking AutoOneToOneField
as a base, it's easy to create a new one that calls upcast
when related objects is requested.
Now profile looks like this:
In order to get users, profile, we just need to write requst.user.profile
.