是否可以动态地将QuerySet模型指定为字符串? [英] Is it possible to specify a QuerySet model dynamically as a string?

查看:60
本文介绍了是否可以动态地将QuerySet模型指定为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Django中动态建立查询.我有很多模型要为其建立查询,但是我不想编码模型的名称,我想将其作为字符串传递.

I am trying to build a query in Django dynamically. I have a lot of models that I would like to build a query for, but I don't want to code the name of the model, I want to pass it as a string.

from django.db.models.query import QuerySet
a_works = QuerySet(model_A)
a_doesnt_work = QuerySet("model_A")  # I want this to work, too

a_works.filter(pk=23)   # no error
a_doesnt_work.filter(pk=23)   # error: AttributeError: 'str' object has no attribute '_meta'

# then I am dynamically filtering different fields, which works fine with a_works
kwargs = { "%s__%s" % (field, oper) : val }
results = a_works.filter( **kwargs )

有没有办法使动态模型选择起作用?

Is there a way to make the dynamic model selection work?

推荐答案

不要尝试通过QuerySet类本身构建查询集.您应该始终通过模型的经理.

Don't try and build querysets via the QuerySet class itself. You should always go via a model's Manager.

您可以通过在 django.db.models 中定义的 get_model 函数获取模型.它带有应用程序名称和型号名称的参数.

You can get the model via the get_model function defined in django.db.models. It takes parameters of the app name and the model name.

from django.db.models import get_model
model = get_model('myapp', 'modelA')
model.objects.filter(**kwargs)

这篇关于是否可以动态地将QuerySet模型指定为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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