【发布时间】:2011-07-29 09:40:48
【问题描述】:
给定一个标识 Django 模型的字符串,我必须获取 <class 'django.db.models.base.ModelBase'> 或 None 类型的关联对象。
我将展示我的解决方案,它工作正常,但看起来很难看。我很高兴知道是否有更好的选择来获得相同的结果。是否存在类似 Django 快捷方式的东西?谢谢。
>>> from django.utils.importlib import import_module
>>> model = 'sandbox.models.Category'
>>> full_name = model.split(".")
>>> module_name = ".".join(full_name[:-1])
>>> class_name = full_name[-1]
>>> model = getattr(import_module(module_name), class_name, None)
>>> type(model)
<class 'django.db.models.base.ModelBase'>
【问题讨论】: