[Answered ]-How to use string values of a variable as a django model queries?

1👍

Use getattr.

Return the value of the named attribute of object. name must be a string.

If this is your input:

reaction = 'sad'

And this is your SocialPost instance:

obj = SocialPost(...)  # Avoid using "object" as a variable name because it is a Python keyword

You can then list all related User records:

reacted_users = getattr(obj, reaction).all()  # Equivalent to <obj.sad.all()>

If you don’t have any validation of the reaction field, you may be interested in hasattr e.g. hasattr(obj, reaction) to verify if the value is a recognized attribute of SocialPost.

Leave a comment