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.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.
I much prefer your first example to your second, but perhaps you could use hasattr(instance,'bank_account')
as a safeguard?
First of all, your first example is the preferred way of doing this (although, you might like to narrow down the except to just the exceptions you expect for this operation).
I imagine that your if statement is blowing up when instance is None
; the solution is to add a test to your if statement, to test instance
first:
if instance and instance.bank_account:
print str(instance.bank_account)
else: print 'No account'
If you don't know if the field exists, you could replace instance.bank_account
with getattr(instance, 'bank_account', None)
, which both retrieves the value, and deals with the possibility of the attribute not existing.
来源:https://stackoverflow.com/questions/9682571/python-test-if-object-exists