Possible Duplicate:
Polymorphism in Django models
I have a Constraint abstract base model which has a foreign key to a Group. Several models inherit from Constraint to behave in a variety of different ways. Here's a (much simplified) version of what I have:
class Constraint(models.Model):
group = models.ForeignKey(Group)
def get_constraint_type(self):
return 'Base'
class meta:
abstract = True
class UserConstraint(Constraint):
user = models.ForeignKey(User)
def get_constraint_type(self):
return 'User'
class ProjectConstraint(Constraint):
project = models.ForeignKey(Project)
def get_constraint_type(self):
return 'Project'
I need to be able to, given a Group, come up with a list of constraint model instances pointing to it.
e.g. if I do
group = ...
constraints = group.constraint_set.all()
for c in constraints:
print c.get_constrait_type()
right now, it will print 'Base' a bunch of times, rather than 'User', 'Project', 'User', etc.
A really hacky solution would be to implement a function like this in the base class:
def get_child(self):
try:
return self.usercontraint
except UserConstraint.DoesNotExist:
pass
try:
return self.projectcontraint
except ProjectConstraint.DoesNotExist:
pass
# etc...
but that seems really terrible. Do any better solutions exist?