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'
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)
exceptbad style, but not if you usedexcept AttributeError. I'd much prefer your first example to your second then.