Reputation: 1118
So this works:
field_name = 'msrp'
price = getattr(mymodel.related_model, field_name)
But I'd like to pass in a variable for the 'related_model', something like:
field_name = 'msrp'
x = related_model_name
price = getattr(mymodel.x, field_name)
Clearly that does not work, but it shows what I'd like to accomplish. Is there a way to pass in a variable as the placeholder for the related model name in some manner?
Upvotes: 1
Views: 80
Reputation: 476659
The price = getattr(mymodel.related_model, 'msrp')
makes not much sense, since this is imply equivalent to price = mymodel.related_model.msrp
. If the name of the related_model
is stored in a variable, you can however use getattr(…)
[python-doc] to obtain the related model object:
x = related_model_name
price = getattr(mymodel, x).msrp
or if both are strings, you can use getattr
twice:
x = related_model_name
msrp = field_name
price = getattr(getattr(mymodel, x), msrp)
Upvotes: 1