1

I have a query

variable3 = "Field3"
variable_gte = "flowrate__gte"
x = mytable.objects.filter(Q((variable_gte, variable2))).order_by(variable3)[0:5]
z = x[0].Field3

How can I call this last value z using variable3, something similar to z = x[0].variable3 If it is impossible, I will need to use if/else condition:

if variable3 = "Field3":
    z = x[0].Field3
else:
    ....

Thank you.

1 Answer 1

1

You can make use of getattr(…) [Django-doc]:

variable3 = 'Field3'
variable_gte = 'flowrate__gte'
x = mytable.objects.filter(
    Q((variable_gte, variable2))
).order_by(variable3)[0:5]

z = getattr(x[0], variable3)

If you write getattr(x, 'y'), this is equivalent to x.y, so you can pass a string with the name of the attribute and obtain the attribute of that name.

It however does not make much sense to first slice, and then obtain the first item. You can remove the …[0:5] part.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for a high quality answer. It solved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.