我想通过字符串名称访问我在django app中定义的模型及其属性。 我找到了这两个解决方案,但它们不适合我的问题。
How to access object attribute given string corresponding to name of that attribute
Python: call a function from string name
例如: models.py
Class Foo(models.Model):
var1 = models.CharField(max_length=20)
var2 = models.CharField(max_length=20)
现在,我有“Foo.var2”字符串,我想访问Foo模型并在其var2字段中进行过滤。
答案 0 :(得分:4)
您可以在包含模型的模块上使用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")