Saturday, 31 August 2013

Combining abstract model class and multi-table inheritance in Django

Combining abstract model class and multi-table inheritance in Django

I have three model classes:
django.contrib.auth.models.User, reffered to as User
mysite.models.Profile, reffered to as Profile
mysite.models.Subscriber, reffered to as Subscriber
Profile inherits from User in a way that is well described in docs as a
solution to add custom properties to User model without bothering with
swappable models (which were only added in version 1.5).
While Profile and Subscriber are different objects, they do share some
properties. Namely, I want to use custom primary key algorithm with both
and override save() method in a similar way, so that code can be reused in
accordance with DRY. Now, if both were plain model classes, that would be
simple:
class BaseProfile(models.Model):
key = models.PositiveIntegerField(primary_key=True)
activated = models.BooleanField(default=False)
...
class Meta:
abstract = True
def save():
...
class Profile(BaseProfile):
...
class Subscriber(BaseProfile):
...
However, Profile already uses multi-table inheritance. I'm thinking of a
way similar to this:
class BaseProfile(models.Model):
key = models.PositiveIntegerField(primary_key=True)
activated = models.BooleanField(default=False)
...
class Meta:
abstract = True
def save():
...
class Profile(BaseProfile, User):
user = models.OneToOneField(User, parent_link=True, blank=True,
null=True, on_delete=models.CASCADE)
...
class Subscriber(BaseProfile):
...
Would that be possible? If so, what order of inheritance is needed in my
case, so that both model fields and save() method are called in a correct
way? Will Meta of both model class not get in conflict?

No comments:

Post a Comment