Advertisement
Guest User

Untitled

a guest
Apr 29th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. from django.db.models.base import ModelBase
  2.  
  3. class InheritanceMetaclass(ModelBase):
  4. def __call__(cls, *args, **kwargs):
  5. obj = super(InheritanceMetaclass, cls).__call__(*args, **kwargs)
  6. return obj.get_object()
  7.  
  8. class Animal(models.Model):
  9. __metaclass__ = InheritanceMetaclass
  10. type = models.CharField(max_length=255)
  11. object_class = models.CharField(max_length=20)
  12.  
  13. def save(self, *args, **kwargs):
  14. if not self.object_class:
  15. self.object_class = self._meta.module_name
  16. super(Animal, self).save( *args, **kwargs)
  17.  
  18. def get_object(self):
  19. if self.object_class in SUBCLASSES_OF_ANIMAL:
  20. self.__class__ = SUBCLASSES_OF_ANIMAL[self.object_class]
  21. return self
  22.  
  23. class Dog(Animal):
  24. class Meta:
  25. proxy = True
  26. def make_sound(self):
  27. print "Woof!"
  28.  
  29.  
  30. class Cat(Animal):
  31. class Meta:
  32. proxy = True
  33. def make_sound(self):
  34. print "Meow!"
  35.  
  36.  
  37. SUBCLASSES_OF_ANIMAL = dict([(cls.__name__, cls) for cls in ANIMAL.__subclasses__()])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement