开发者社区> 问答> 正文

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

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

shop_users = ShopUsers.objects.get(pk=_id)
然后,如果对象存在,我正在为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
}

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

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

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

使用(... if ... else)处理AttributeError有什么技巧吗?

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

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

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

展开
收起
一码平川MACHEL 2019-01-21 11:30:06 1963 0
1 条回答
写回答
取消 提交回答
  • getattr 完全按照你的意愿行事。

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

    'shop': getattr(shop_users.shop,'title', None)
    根据getattr文件:

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

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

    2019-07-17 23:26:04
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
继承与功能组合 立即下载
对象的生命期管理 立即下载
低代码开发师(初级)实战教程 立即下载