Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 937
stett Avatar asked Oct 14 '25 11:10

stett


1 Answers

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

How to get foreign key values with getattr from models

like image 200
anuragal Avatar answered Oct 17 '25 15:10

anuragal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!