Python测试对象是否存在

2024-04-28 14:47:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我认为使用try:except:for流控制是不好的风格,但是我不知道如何编写以下代码来测试Django中是否存在DB字段。这是“脏”代码,可以工作:

@receiver(pre_save, sender=UserProfile)
def create_user_profile(sender, instance=None, **kwargs):

    try:
        print str(instance.bank_account)
    except:
        print 'No account'

我宁愿这样做,但是当运行if语句并且对象不存在时,我会得到一个异常:

@receiver(pre_save, sender=UserProfile)
def create_user_profile(sender, instance=None, **kwargs):

    if instance.bank_account is None:
        print 'No account'
    else:
        print str(instance.bank_account)

Tags: instance代码nonesavedefcreateaccountpre