django 是否可以将QuerySet模型动态指定为字符串?

0vvn1miw  于 2023-01-21  发布在  Go
关注(0)|答案(2)|浏览(139)

我尝试在Django中动态地构建一个查询,我有很多模型,我想为它们构建一个查询,但是我不想编码模型的名称,我想把它作为一个字符串传递。

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 )

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

nxowjjhe

nxowjjhe1#

不要尝试通过QuerySet类本身构建查询集,你应该总是通过模型的管理器。
可以通过django.db.models中定义的get_model函数获取模型,该函数的参数为应用名称和模型名称。

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

3df52oht2#

参考:https://stackoverflow.com/a/75168880/7212249

from django.apps import apps

def get_app_label_and_model_name(instance: object):
"""
    get_model(), which takes two pieces of information — an “app label” and “model name” — and returns the model
     which matches them.
@return: None / Model
"""
app_label = instance._meta.app_label
model_name = instance.__class__.__name__
model = apps.get_model(app_label, model_name)
return model

如何使用?

model_name = get_app_label_and_model_name(pass_model_object_here)

并使用它来获取查询的动态模型名称

model_name = get_app_label_and_model_name(pass_model_object_here)
query_set = model_name.objects.filter() # or anything else

相关问题