Feb 18, 2010

User profiles with inheritance in Django

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.

Simple solution

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.


class UpCastModel(models.Model):
    Base class for models that are ment to be inherited.
    Introduces upcast method that returns child instance.
    final_type = models.ForeignKey(ContentType, editable=False)

    def save(self, args, **kwargs):
        if not
            self.final_type = ContentType.objects.get_for_model(type(self))
        super(UpCastModel, self).save(args, **kwargs)

    def upcast(self):
        if not hasattr(self, '_upcast'):
            if self.final_type.model_class == self.class:
                self._upcast = self
                self._upcast = self.final_type.get_object_for_this_type(
        return self._upcast

    class Meta:
        abstract = True

class UpCastSingleRelatedObjectDescriptor(SingleRelatedObjectDescriptor):

    def get(self, instance, instance_type=None):
        parent = super(
            UpCastSingleRelatedObjectDescriptor, self
        ).get(instance, instance_type)
        return parent.upcast()

class UpCastOneToOneField(models.OneToOneField):
    UpCastOneToOneField gets child of related object.
    def contribute_to_related_class(self, cls, related):
            cls, related.get_accessor_name(),

Now profile looks like this:

class BaseProfile(UpcastModel):
    user = UpCastOneToOneField(User)

class BoyProfile(BaseProfile):

class GirlProfile(CitizenProfile):

In order to get users, profile, we just need to write requst.user.profile.

Subscribe for the news and updates

More thoughts
Dec 13, 2022Technology
How to create a timelapse video from frames

We’ll tell you how to create a video timelapse from a sequence of snapshots and provide customers with video playlists optimized for browser playback.

Nov 29, 2022Technology
React Performance Testing with Jest

One of the key requirements for modern UI is being performant. No matter how beautiful your app looks and what killer features it offers, it will frustrate your users if it clangs.

Jan 12, 2017Technology
Making Custom Report Tables Using AngularJS and Django

In this article I will tell you how to create an interactive interface with a widely customized visual look and different filtering to view reports.

Jan 9, 2017Technology
How to Use GraphQL with Django

GraphQL is a very powerful library, which is not difficult to understand. GraphQL will help to write simple and clear REST API to suit every taste and meet any requirements.

Aug 31, 2016Technology
Angular vs React Comparison

In this article, we will compare two most popular JS Libraries (Angular vs React). Both of them were created by professionals and have been used in famous big projects.

Feb 28, 2010Technology
Composing multiple views in Django

In UNIX way, each view should solve single task. This is good idea, but sometimes we need to mix logic of different views on same page. Filter, sort, paginate, or, for example, add comment on product page. In this article I'll show how we can mix such multiple views.