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)
I’m guessing you encounter a
BankAccount.DoesNotExisterror? If that’s the case, you could reverse the relationship betweenUserProfileandBankAccount. 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...exceptinstead of a workaround, unless that workaround actually makes sense.