3

I want to access to a model and its attribute that I defined in my django app via string name. I found these two solutions but they are not fit to my question.

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

Python: call a function from string name

for example: models.py

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

Now, I have "Foo.var2" string and I want to access to Foo model and filter in its var2 field.

Community
  • 1
  • 1

1 Answers1

4

You can use getattr on the module containing the model, and then apply the same on the model to get the field in the model:

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")
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139