Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django 1.9中访问名称为字符串的模型_Python_Django - Fatal编程技术网

Python 如何在django 1.9中访问名称为字符串的模型

Python 如何在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

我想通过字符串名称访问我在django应用程序中定义的模型及其属性。 我找到了这两种解决方案,但它们不适合我的问题

例如: models.py

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

你是怎么弄到那根绳子的?