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

2

5

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')
Feretory answered 13/9, 2010 at 8:33 Comment(0)
M
14

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')()
Merganser answered 13/9, 2010 at 8:37 Comment(1)
thanks.. ok I get it now.. I had tried doing something like this before, but was putting it all into just one getattr call, I understand now that I am just calling the 'all' part with the rest of the "preceding part" as the object in the getattr, so that needs to be done separately, thanks for clearing this up... I had thought I could do: dbobject = getattr(model,'objects.all')() but this wasn't working so this kind of confused me from thereFeretory
L
2

You will need to call the attribute if it's a function, e.g.

ret = getattr(mymodel,'objects')
all = getattr(ret,'all')
self.dbobject = all()
Larva answered 13/9, 2010 at 8:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.