Back
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:

request.user.get_profile().get_final_profile()

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.

Upcast

Allows to get sublass instance from base class instance.

AutoOneToOneField

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.

Solution

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.pk:
            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
            else:
                self._upcast = self.final_type.get_object_for_this_type(id=self.pk)
        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):
        setattr(
            cls, related.get_accessor_name(),
            UpCastSingleRelatedObjectDescriptor(related)
        )

Now profile looks like this:

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


class BoyProfile(BaseProfile):
    pass


class GirlProfile(CitizenProfile):
    pass

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

Subscribe for the news and updates

More thoughts
Nov 27, 2024Technology
Stoicism At Work

This article explores how Stoic principles can be applied in the workplace to navigate stress, improve self-control, and focus on what truly matters, with practical examples from the author’s experience in software development.

May 5, 2023Technology
The best CSS trends for 2023

Cascading Style Sheets (CSS) made its debut in 1996 and continue to be an indispensable and evolving component of web development. We will examine the most valuable recent and upcoming characteristics in CSS for this year.

Dec 8, 2022Technology
How to create a route finder on an SVG map

In one of our recent projects, we had an interesting case: the whole application was built around an interactive map for a fairly large shopping mall, and the main goal of the system was to plot the closest route to a user-selected destination.

Oct 3, 2016Technology
How to include JQuery plugins in Angular 2 running via webpack

Learn more about how to include jquery plugins in angular 2 running via webpack. Our tutorial is perfect for Angular beginners.

Oct 11, 2010Technology
Char search in Emacs as in Vim

In VIM there is a command for char search: f. After first use it can be repeated with ;. I like to navigate in line with it. You see that you need to go to bracket in a middle of a line - you press f( and one-two ; and you are there. There's no such command in Emacs, so I had to write my own. I've managed even to implement repetition with ;.

Sep 23, 2010Technology
Dynamic class generation, QuerySetManager and use_for_related_fields

It appears that not everyone knows that in python you can create classes dynamically without metaclasses. I'll show an example of how to do it.So we've learned how to use custom QuerySet to chain requests:Article.objects.old().public()Now we need to make it work for related objects:user.articles.old().public()This is done using use_for_related_fields, but it needs a little trick.