我正在使用Django 1.3.1,我有以下模型:
class masterData(models.Model):
uid = models.CharField(max_length=20,primary_key=True)
class Meta:
abstract = True;
class Type1(masterData):
pass;
class Type2(masterData):
pass;
现在,我正在尝试获取masterData的所有子类的列表。一世 尝试过:
masterData.__subclasses__()
我发现上述非常有趣的事情就是它 在 python manage.py shell 中完美运行,并且不完全可以正常工作 在运行网络服务器时!
那么如何获取从抽象基类模型派生的模型列表?
谢谢:)
答案 0 :(得分:0)
Metaclass for defining Abstract Base Classes (ABCs).
Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in
class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs
as 'virtual subclasses' -- these and their descendants will be considered subclasses of the
registering ABC by the built-in issubclass() function, but the registering ABC won't show up in
their MRO (Method Resolution Order) nor will method implementations defined by the registering
ABC be callable (not even via super()).
我没有太多使用过ABCMeta(实际上今天有点......)。您需要使用'issubclass()'函数 因为ABC不会出现在他们身上。
如果您使用了继承,子类()将起作用。
>>> class foo(object):
... pass
...
>>> class bar(foo):
... pass
...
>>> a = bar()
>>> a.__class__.__mro__
(<class '__main__.bar'>, <class '__main__.foo'>, <type 'object'>)
>>> foo.__subclasses__()
[<class '__main__.bar'>]