In Django, can I use a variable passed to a function in order to access and attribute of a model?
I'm trying to create a custom function where one of the variables passed is the name of an attribute of a model. I'm doing this to try to access the underlying value.
def tabsums(entity_object, year_object, columntitle):
curassetobject = BSAccountType.objects.get(name = "Current asset", company = entity_object)
curassetsum = BSSum.objects.get(Q(company = entity_object) & Q(year = year_object) & Q(account_type = curassetobject)).columntitle
Essentially, I want columntitle to be a string that matches the model field name so I'm trying to pass the variable as the attribute name to access the underlying value. It's not working as Django/python is looking for the attribute "columntitle" which does not exist, rather than looking to the underlying string.
Is there a syntax I can use that will allow Django to utilize the underlying string value that is passed?
Thank you very much.
I haven't tested this, but Django is essentially just python, so you should be able to use the getattr() function to do what you want. Something like this:
def tabsums(entity_object, year_object, columntitle):
curassetobject = BSAccountType.objects.get(name = "Current asset", company = entity_object)
curassetsum = getattr(BSSum.objects.get(Q(company = entity_object) & Q(year = year_object) & Q(account_type = curassetobject)), columntitle)