如何动态检索Django模型类? [英] How do I retrieve a Django model class dynamically?

查看:90
本文介绍了如何动态检索Django模型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有Django模型的完整模块路径,是否可以执行以下操作:

Without having the full module path of a Django model, is it possible to do something like:

model = 'User' [in Django namespace]
model.objects.all()

... as反对:

User.objects.all().

编辑:我正在尝试根据命令行输入进行此调用。可以避免import语句,例如,

I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g.,

model = django.authx.models.User

没有Django返回错误:

Without Django returning the error:

"global name django is not defined."


推荐答案

我想你在寻找:来自django.db.models.loading的

I think you're looking for this:

from django.db.models.loading import get_model
model = get_model('app_name', 'model_name')

当然还有其他的方法,但是如果你不知道您需要导入到命名空间中的模型文件。 (注意,没有办法安全地得到一个模型,而不知道它属于什么应用程序。如果要在所有应用程序的模型中迭代测试你的运气,请查看源代码以加载.py。)

There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.)

更新:根据Django的弃用时间轴 django.db.models.loading 已在Django 1.7中弃用,将会在Django 1.9中删除。如 Alasdair的回答所指出的,动态加载模型的新API已添加到Django 1.7中。

Update: According to Django's deprecation timeline, django.db.models.loading has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in Alasdair's answer, a new API for dynamically loading models was added to Django 1.7.

这篇关于如何动态检索Django模型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆