Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get foreign key values with getattr from models

I have a model Project and i am getting the attributes of that with the following instr

attr = getattr(project, 'id', None)

project is the instance, id is the field and None is the default return type.

My question is: what if I want to get the Foreign Key keys with this?

Get customer name

project.customer.name How to get customer name with the above condition?

Already Tried

if callable(attr):
     context[node][field] = '%s' % attr()

Current Code

context = {'project': {}}
fields = ('id', 'name', 'category', 'created_by', customer)

for field in fields:
    attr = getattr(project, field, None)
        if callable(attr):
            context['project'][field] = '%s' % attr()
        else:
            context['project'][field] = attr

i need to adjust customer object here. that i can give something like customer__name or customer.name in my fields and it get populated with the name of the customer, but i am not sure.

like image 899
A.J. Avatar asked Nov 27 '13 06:11

A.J.


People also ask

What is getattr() used for?

The getattr() function returns the value of the specified attribute from the specified object.

How to get value of an object in Python?

Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function.

How to use get attribute in Python?

getattr() Parameters getattr() method takes multiple parameters: object - object whose named attribute's value is to be returned. name - string that contains the attribute's name. default (Optional) - value that is returned when the named attribute is not found.

Is Getattr slow python?

Yes, compared to the direct conventional method of accessing an attribute of a given object, the performance of getattr() is slower.


1 Answers

You can do something like follows:

def get_repr(value): 
    if callable(value):
        return '%s' % value()
    return value

def get_field(instance, field):
    field_path = field.split('.')
    attr = instance
    for elem in field_path:
        try:
            attr = getattr(attr, elem)
        except AttributeError:
            return None
    return attr

for field in fields:
    context['project'][field] = get_repr(get_field(project, field))
like image 103
alko Avatar answered Oct 25 '22 01:10

alko