stett
stett

Reputation: 1411

Access model's foreign key related fields using a string?

A similar question was asked here: Access Django model's fields using a string instead of dot syntax?

I want to be able to access the value of a foreign-key related field in a django model, based on a dynamically generated string. For example, to get a direct field value you would use:

getattr(instance, 'name')

But I want to be able to follow foreign key relations, perhaps like so:

model_getattr(instance, 'name__othername')

This would require another query, and it might be possible to write the function model_getattr by splitting the attribute string on '__'. But I'm curious to know if there's a "correct" way to do this? Is it even possible?

UPDATE:

I managed to write a function that does what I need, but I would still like to know if there's a preferred way. This solution is obviously not as efficient as it could be, but it works for now:

def get_attribute(instance, name):

    if hasattr(instance, name):
        return getattr(instance, name)

    names = name.split('__')
    name = names.pop(0)
    if len(names) == 0:
        return None

    if hasattr(instance, name):
        value = getattr(instance, name)
        return get_attribute(value, '__'.join(names))

    return None

Upvotes: 4

Views: 4718

Answers (1)

Anurag
Anurag

Reputation: 3114

I think you need something which is already discussed in below thread

How to get foreign key values with getattr from models

Upvotes: 3

Related Questions