人类已知的唯一方法是使用元类编程。
这是简短的回答:
from django.db.models.base import ModelBase
class InheritanceMetaclass(ModelBase):
def __call__(cls, *args, **kwargs):
obj = super(InheritanceMetaclass, cls).__call__(*args, **kwargs)
return obj.get_object()
class Animal(models.Model):
__metaclass__ = InheritanceMetaclass
type = models.CharField(max_length=255)
object_class = models.CharField(max_length=20)
def save(self, *args, **kwargs):
if not self.object_class:
self.object_class = self._meta.module_name
super(Animal, self).save( *args, **kwargs)
def get_object(self):
if not self.object_class or self._meta.module_name == self.object_class:
return self
else:
return getattr(self, self.object_class)
class Dog(Animal):
def make_sound(self):
print "Woof!"
class Cat(Animal):
def make_sound(self):
print "Meow!"
和期望的结果:
shell$ ./manage.py shell_plus
From 'models' autoload: Animal, Dog, Cat
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> dog1=Dog(type="Ozzie").save()
>>> cat1=Cat(type="Kitty").save()
>>> dog2=Dog(type="Dozzie").save()
>>> cat2=Cat(type="Kinnie").save()
>>> Animal.objects.all()
[<Dog: Dog object>, <Cat: Cat object>, <Dog: Dog object>, <Cat: Cat object>]
>>> for a in Animal.objects.all():
... print a.type, a.make_sound()
...
Ozzie Woof!
None
Kitty Meow!
None
Dozzie Woof!
None
Kinnie Meow!
None
>>>
它是如何工作的?
- 存储有关动物类名的信息 - 我们使用 object_class
- 删除“代理”元属性 - 我们需要在 Django 中反转关系(不好的一面是我们为每个子模型创建额外的数据库表并为此浪费额外的数据库命中,好的一面是我们可以添加一些子模型相关的字段)
- 为 Animal 自定义 save() 以将类名保存在调用 save 的对象的 object_class 中。
- 需要方法 get_object 来通过 Django 中的反向关系引用名称缓存在 object_class 中的模型。
- 每次通过重新定义 Animal 模型的 Metaclass 实例化 Animal 时,都会自动执行此 .get_object()“强制转换”。元类类似于类的模板(就像类是对象的模板一样)。
有关 Python 中元类的更多信息:http: //www.ibm.com/developerworks/linux/library/l-pymeta.html