Monday, March 2, 2015

Re: Traversing relationships based on lookup strings

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:


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 <francis@devrx.org> 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 django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
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 django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
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%2BciWP%2BZ9A_D%3DCxrPfgoUVZEtN3FLWe_eQSmpwN7eD9sJrFw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment