Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class PolyMorphicModel(models.Model):
- class meta:
- proxy = True
- __type = models.CharField( max_length = 100 )
- def save(self, *args, **kwargs):
- """
- set the correct type before saving
- """
- self.__type=self.__class__.__name__.lower()
- if (self.__type == 'vehicle'):
- raise NotImplementedError()
- super(Vehicle, self).save(*args, **kwargs)
- def get_child_object(self):
- """
- Returns the correct child object for an instance
- """
- if (self.__type == 'vehicle'):
- raise NotImplementedError()
- return getattr(self, self.__type)
- class Vehicle(PolyMorphicModel):
- color = models.CharField( max_length = 100 )
- class Car(Vehicle):
- model = models.CharField( max_length = 100 )
- class Boat(Vehicle):
- captain = models.CharField( max_length = 100 )
- audi = Car(model='audi', color='red')
- audi.save()
- car = Vehicle.objects.get(id=audi.id).get_child_object()
- assert car.color=='red'
- assert car.model=='audi'
- ship = Boat(color = 'black', captain = 'Hook')
- ship.save()
- boat = Vehicle.objects.get(id=ship.id).get_child_object()
- assert boat.captain == 'Hook'
- assert boat.color == 'black'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement