【问题标题】:AtributteError "object has no attribute" - how to prevent without try/except - accessing model fieldAtributeError "object has no attribute" - 如何在没有 try/except 的情况下防止 - 访问模型字段
【发布时间】: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


    【解决方案1】:

    getattr 做你想做的事。

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

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

    根据getattrdoc

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

    从对象中获取命名属性; getattr(x, 'y') 等价于 x.y。 当给定默认参数时,当属性没有时返回 存在;没有它,在这种情况下会引发异常。

    【讨论】:

    猜你喜欢
    • 2023-02-22
    • 2022-11-20
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多