whitebear
whitebear

Reputation: 12423

Use variable as key name for model

I have the method like this.

@classmethod
def get_my_msg(cls):
    return cls.objects.latest("updated_at").my_msg

Now , I want to give the variable to function and get the data dynamically such as

@classmethod
def get_my_msg(cls,key):
    return cls.objects.latest("updated_at").{key} // use variable here

Is it possible?

Upvotes: 1

Views: 82

Answers (1)

Wariored
Wariored

Reputation: 1343

You can use Python gettattr

@classmethod
def get_my_msg(cls,key):
    res = cls.objects.latest("updated_at")
    return getattr(res, key)

Upvotes: 1

Related Questions