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

查看:20
本文介绍了如何动态检索 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()

...相对于:

User.objects.all().

我正在尝试根据命令行输入进行此调用.是否可以避免导入语句,例如,

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."

推荐答案

我认为您正在寻找这个:

I think you're looking for this:

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

当然还有其他方法,但如果您不知道需要将哪个模型文件导入到您的命名空间,我会采用这种方法.(请注意,在不知道模型属于哪个应用的情况下,真的无法安全地获取模型.如果您想测试迭代所有应用模型的运气,请查看 loading.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 1.7+ 的更新: 根据 Django 的 弃用时间线django.db.models.loading 已在 Django 1.7 中弃用,并将在 Django 1.9 中删除.正如Alasdair 的回答 中指出的那样,在 Django 1.7+ 中,有一个 applications registry.您可以使用 apps.get_model动态获取模型的方法:

Update for Django 1.7+: 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, In Django 1.7+, there is an applications registry. You can use the apps.get_model method to dynamically get a model:

from django.apps import apps
MyModel = apps.get_model('app_label', 'MyModel')

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

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