Python 如何在django 1.9中访问名称为字符串的模型
我想通过字符串名称访问我在django应用程序中定义的模型及其属性。 我找到了这两种解决方案,但它们不适合我的问题 例如: models.pyPython 如何在django 1.9中访问名称为字符串的模型,python,django,Python,Django,我想通过字符串名称访问我在django应用程序中定义的模型及其属性。 我找到了这两种解决方案,但它们不适合我的问题 例如: models.py Class Foo(models.Model): var1 = models.CharField(max_length=20) var2 = models.CharField(max_length=20) 现在,我有了“Foo.var2”字符串,我想访问Foo模型并在其var2字段中进行筛选。您可以在包含模型的模块上使用getatt
Class Foo(models.Model):
var1 = models.CharField(max_length=20)
var2 = models.CharField(max_length=20)
现在,我有了“Foo.var2”字符串,我想访问Foo模型并在其var2字段中进行筛选。您可以在包含模型的模块上使用
getattr
,然后在模型上应用相同的方法来获取模型中的字段:
from app_name import models
s = "Foo.var2"
attrs = s.split('.')
my_model = my_field = None
# get attribute from module
if hasattr(models, attrs[0]):
my_model = getattr(models, attrs[0])
# get attribute from model
if hasattr(my_model, attrs[1]):
my_field = getattr(my_model, attrs[1])
# and then your query
if my_model and my_field:
q = my_model.objects.filter(my_field="some string literal for filtering")
你是怎么弄到那根绳子的?