Whoops, I meant to swap out 'item' for 'instance' to make it a bit more readable, but got myself distracted and forgot to finish and hit send.
So, s/item/instance/... HTH, -James On Mon, Mar 2, 2015 at 2:11 PM, James Schneider <[email protected]> wrote: > Nothing in Django specifically that I'm aware of (although that's not > saying much), but you can probably do something pretty slick with the > operator library and attrgetter: > > https://docs.python.org/2/library/operator.html#operator.attrgetter > > It would probably look something like this (untested): > > > # define a function to pull the nested attribute > # assume this is in myapp/utils.py > def get_item_attr(obj_instance, search_string): > dotted_string = search_string.replace('__', '.') > instance_attr = operator.attrgetter(dotted_string) > instance_attr_value = instance_attr(obj_instance) > return item_attr_value > > > # later, in a view, maybe... > from myapp.utils import get_item_attr > booking_client_name = get_item_attr(trip, 'booking__client__name') > > > Obviously this is naive and you'll need to check for failures at various > points and raise some exceptions if attributes can't be found/accessed, but > I think this may point you in the right direction. > > Never tried this on my own so YMMV. Note that you'll incur multiple DB > hits using a function like this (for the FK traversals), so be careful if > you plan to run such a function several times for a single request. > > -James > > > On Mon, Mar 2, 2015 at 10:54 AM, Francis Devereux <[email protected]> > wrote: > >> Hi, >> >> Is there a Django function that takes a model instance and a lookup >> string, and returns the value of the related field? >> >> For example: >> >> the_function_i_am_looking_for(trip, 'booking__client__name') >> >> would return the same as: >> >> trip.booking.client.name >> >> Thanks, >> >> Francis >> >> -- >> You received this message because you are subscribed to the Google Groups >> "Django users" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to [email protected]. >> To post to this group, send email to [email protected]. >> Visit this group at http://groups.google.com/group/django-users. >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/django-users/FB0F25B1-00B0-4CD5-A62D-B9CE44F189C8%40devrx.org >> . >> For more options, visit https://groups.google.com/d/optout. >> > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciVF5r2cqguM%2BLfOXT0x32ZncseAbOYOpfsQaPeLEROfgQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.

