AtributteError"对象没有属性" - 如何防止没有try/except - 访问模型字段

Adr*_*eja 3 python django attributes nested-attributes

我有一个问题:(我正在研究Django 1.8,Python 2.7.15)我从数据库中获取了一个对象:

shop_users = ShopUsers.objects.get(pk=_id)
Run Code Online (Sandbox Code Playgroud)

然后,如果对象存在,我正在为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
    }
Run Code Online (Sandbox Code Playgroud)

但是shop_users.price.title可能不存在.

我想在我准备上面的数据时检查它(我正在做'...如果......其他'),但如果shop_users.price.title不存在则提供AttributeError.

我可以在'data'声明之前使用try/except但这会使我的代码加倍...

有没有处理AttributeError的技巧(... if ... else)?

也许shop_users.price.title [0](不起作用)

或者获取(shop_users.price.title)?

我只是不想加倍我的代码...但我不知道任何诀窍:/

我很年轻.我感谢任何帮助!

Meh*_*far 6

getattr 完全按照你的意愿行事.

试试这个而不是'shop': shop_users.shop.title:

'shop': getattr(shop_users.shop,'title', None)
Run Code Online (Sandbox Code Playgroud)

根据getattr文件:

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

从对象获取命名属性; getattr(x,'y')等价于xy当给出一个默认参数时,当属性不存在时返回它; 没有它,在这种情况下会引发例外.