【问题标题】:How to access a model with its name in a string in django 1.9如何在 django 1.9 中使用字符串中的名称访问模型
【发布时间】:2016-10-30 20:17:03
【问题描述】:

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

How to access object attribute given string corresponding to name of that attribute

Python: call a function from string name

例如: 模型.py

Class Foo(models.Model):
    var1 = models.CharField(max_length=20)
    var2 = models.CharField(max_length=20)

现在,我有“Foo.var2”字符串,我想访问 Foo 模型并在其 var2 字段中进行过滤。

【问题讨论】:

  • 你是怎么得到那个字符串的?

标签: python django


【解决方案1】:

您可以在包含模型的模块上使用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")

【讨论】:

    猜你喜欢
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 2015-06-18
    • 2011-05-04
    • 2016-04-14
    • 2014-08-20
    • 2016-12-24
    相关资源
    最近更新 更多