Python test if object exists

主宰稳场 提交于 2019-12-22 01:26:15

问题


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)

回答1:


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.




回答2:


I much prefer your first example to your second, but perhaps you could use hasattr(instance,'bank_account') as a safeguard?




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!