[Django]-Is there a sane way to simulate virtual inheritance in Django models?

2👍

Yes, this is probably the wrong paradigm. It’s easy to be misled by the object-relational mapper (ORM) – database tables don’t really map all that well to objects, and this difference is known as the object-relational impedance mismatch.

What you actually need is to make action a field. This field can take a choices parameter which represents the possible values of that field – ie logged in or logged out:

class LoggedAction(models.Model):
    ACTIONS = (
       ('I', 'logged in'),
       ('O', 'logged out')
    )
    user = models.ForeignKey(User)
    timestamp = models.DateTimeField(auto_now_add=True)
    action = models.CharField(max_length=1, choices=ACTIONS)

    def __unicode__(self):
        return u"%s: %s %s" % (self.timestamp, self.user, self.get_action_display())

Note that I’ve used arbitrary single-character strings to represent the actions, and the get_action_display() magic method to get the full description.

1👍

Have a look at InheritanceManager from django-model-utils. It allows you to get the concrete subclasses.

Leave a comment