This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but nowadays it is usually simpler to use import hooks (see PEP 302). Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime.
from models import Song, Lyrics, Composers, BlaBla
def xyz(request):
try:
modelname = get_model_name_somehow(request):
model =globals()[modelname]
model.objects.all()
except KeyError:
pass # Model/Module not loaded ... handle it the way you want to
我很确定你想要
__import__()
。在读这个:docs.python.org: ^{}
似乎您希望加载手头上所有可能匹配的模块/模型,并根据请求选择一个特定的模块/模型来使用。您可以使用“globals()”返回全局级变量的字典,该字典可通过字符串进行索引。所以如果你做类似globals()['Song']的操作,它会给你一个歌曲模型。这很像PHP的$$,只是它只获取全局范围的变量。对于局部作用域,必须调用locals()。在
下面是一些示例代码。在
相关问题 更多 >
编程相关推荐