【发布时间】:2012-03-13 10:49:20
【问题描述】:
我认为使用 try: except: 进行流控制是不好的风格,但我不知道如何编写以下代码来测试 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)
【问题讨论】:
-
为什么该字段永远不存在?
-
第一次创建和保存之前
-
出于好奇:您是遵循项目指南还是个人喜好?我会认为您不合格的
except风格不好,但如果您使用except AttributeError,则不会。我更喜欢你的第一个例子而不是你的第二个例子。 -
Python 是一种鼓励“请求宽恕,而不是许可”的语言。除非您认为该帐户大部分时间不存在的可能性更大,否则只需捕获一个(特定)异常。 docs.python.org/glossary.html#term-eafp
标签: python django object flow-control