Reputation: 311
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.
Upvotes: 1
Views: 39
Reputation: 476557
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.
Upvotes: 1