Search code examples
pythondjangoattributesnested-attributes

AtributteError "object has no attribute" - how to prevent without try/except - accessing model field


I have a question: (I'm working on Django 1.8, Python 2.7.15) I'm getting an object from the database:

shop_users = ShopUsers.objects.get(pk=_id)

Then if the object exists I am preparing data for View:

if shop_users:
    data = {
        'full_name': shop_users.full_name,
        'shop': shop_users.shop.title,
        'price_title': shop_users.price.title if shop_users.price.title else '',
        'package_price': shop_users.price.price,
        'user_price': shop_users.payment.operation_amount
    }

But there is a possibility that shop_users.price.title won't exist.

I would like to check it right while I prepare data like above (I'm doing '... if ... else'), but if shop_users.price.title does not exist it provides AttributeError.

I can use try/except before 'data' declaration but this will double my code...

Is there any trick for handling AttributeError with (... if ... else)?

Maybe shop_users.price.title[0] (does not work)

or get(shop_users.price.title) ?

I just don't want to double my code... but I don't know any trick for this :/

I'm junior. I appreciate any help!


Solution

  • getattr exactly do what you looking for.

    Try this instead of 'shop': shop_users.shop.title:

    'shop': getattr(shop_users.shop,'title', None)
    

    according to getattr doc:

    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case.