Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. class PolyMorphicModel(models.Model):
  2.     class meta:
  3.         proxy = True
  4.     __type  = models.CharField( max_length = 100 )
  5.     def save(self, *args, **kwargs):
  6.         """
  7.        set the correct type before saving
  8.        """
  9.         self.__type=self.__class__.__name__.lower()
  10.         if (self.__type == 'vehicle'):
  11.             raise NotImplementedError()
  12.         super(Vehicle, self).save(*args, **kwargs)
  13.  
  14.     def get_child_object(self):
  15.         """
  16.        Returns the correct child object for an instance
  17.        """
  18.         if (self.__type == 'vehicle'):
  19.             raise NotImplementedError()
  20.         return getattr(self, self.__type)
  21.  
  22. class Vehicle(PolyMorphicModel):
  23.     color = models.CharField( max_length = 100 )
  24.      
  25. class Car(Vehicle):
  26.     model = models.CharField( max_length = 100 )
  27.  
  28. class Boat(Vehicle):
  29.     captain = models.CharField( max_length = 100 )
  30.  
  31. audi = Car(model='audi', color='red')
  32. audi.save()
  33. car = Vehicle.objects.get(id=audi.id).get_child_object()
  34. assert car.color=='red'
  35. assert car.model=='audi'
  36.  
  37. ship = Boat(color = 'black', captain = 'Hook')
  38. ship.save()
  39. boat = Vehicle.objects.get(id=ship.id).get_child_object()
  40. assert boat.captain == 'Hook'
  41. assert boat.color == 'black'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement