Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, Django, how to use getattr (or other method) to call object that has multiple attributes?

After trying to get this to work for a while and searching around I am truly stumped so am posting here... I want to make some functions in classes that I am writing for django as generic as possible so I want to use getattr to call functions such as the one below in a generic manner:

the way I do it that works (non-generic manner):

from django.db.models import get_model
mymodel = get_model('appname', 'modelname')
dbobject = mymodel.objects.all()

one of my attempts create this in a generic manner, still not working, it does return something back but its not the proper object type so that i can get the data from it (its a database call for django)

ret = getattr(mymodel,'objects')
dbobject = getattr(ret,'all')
like image 449
Rick Avatar asked Sep 13 '10 08:09

Rick


People also ask

Does Getattr work with methods?

Okay, so it's cool that you can use getattr to get methods as well as properties, but how does that help us? Well, this can definitely be useful in keeping your code DRY if you have some common logic surrounding branching method calls.

What would happen if Getattr () tried to retrieve an attribute of an object that did not exist?

The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

What does __ Getattr __ do in python?

Python getattr() function. Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned.

What is Getattr () used for * What is Getattr () used for to delete an attribute to check if an attribute exists or not to set an attribute?

Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key. Parameters : obj : The object whose attributes need to be processed. key : The attribute of object.


1 Answers

You forgot to call the result.

dbobject = mymodel.objects.all()

Accesses the method mymodel.objects.all and then calls it.

ret = getattr(mymodel,'objects')
self.dbobject = getattr(ret,'all')

accesses the method mymodel.objects.all but does not call it.

All you need is to change the last line to:

self.dbobject = getattr(ret,'all')()
like image 141
Duncan Avatar answered Sep 28 '22 09:09

Duncan