【发布时间】:2019-01-08 09:53:04
【问题描述】:
我有一个问题: (我正在开发 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 有可能不存在。
我想在准备上述数据时正确检查它(我正在做'... if ... else'),但如果 shop_users.price.title 不存在,它会提供 AttributeError。
我可以在“数据”声明之前使用 try/except,但这会使我的代码加倍...
用 (... if ... else) 处理 AttributeError 有什么技巧吗?
也许 shop_users.price.title[0](不起作用)
或获取(shop_users.price.title)?
我只是不想加倍我的代码...但我不知道任何技巧:/
我是小学生。我很感激任何帮助!
【问题讨论】:
标签: python django attributes nested-attributes