Python测试是否存在对象 [英] Python test if object exists
问题描述
我认为使用try的不好的风格:除了:对于流控制,但是我无法弄清楚如何编写以下代码来测试Django中的DB字段是否存在。这是肮脏的代码:
I consider it bad style to use try: except: for flow control, but I can't figure out how to write the following code to test if a DB field in Django exists. This is the "dirty" code which works:
@receiver(pre_save, sender=UserProfile)
def create_user_profile(sender, instance=None, **kwargs):
try:
print str(instance.bank_account)
except:
print 'No account'
我宁愿做这样的事情,但是当 if
语句运行,对象不存在:
I would rather wanna do something like this, but I get an exception when the if
statement is run and the object does not exist:
@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)
推荐答案
猜测你遇到一个 BankAccount.DoesNotExist
错误?如果是这样,您可以扭转 UserProfile
和 BankAccount
之间的关系。看看 Django ticket#10227 了解这里发生了什么。
I'm guessing you encounter a BankAccount.DoesNotExist
error? If that's the case, you could reverse the relationship between UserProfile
and BankAccount
. Have a look at Django ticket #10227 to find out what's going on here.
就是说,如果我需要使用你的代码,我宁愿看到一个明确的尝试...除了
而不是一个解决方法,除非该解决方法实际上是有意义的。
That being said, if I needed to work with your code I'd rather see an explicit try...except
instead of a workaround, unless that workaround actually makes sense.
这篇关于Python测试是否存在对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!