在Django / Python中,什么是更好的做法,检查对象是否存在于Model Manager
之外或调用它的Method
上?例如,
管理器:
class CustomerReferralManager(models.Manager):
def get_referral(self, mobile_number, campaign):
try:
return self.objects.filter(mobile=mobile_number).get()
except self.DoesNotExist:
pass
方法:
referral = CustomerReferral.objects.get_referral(mobile_number=mobile, campaign=campaign)
if referral:
referral.complete_referral()
或者......
管理器:
class CustomerReferralManager(models.Manager):
def get_referral(self, mobile_number, campaign):
return self.objects.filter(mobile=mobile_number).get()
方法:
try:
referral = CustomerReferral.objects.get_referral(mobile_number=mobile, campaign=campaign)
referral.complete_referral()
except self.DoesNotExist:
pass
答案 0 :(得分:1)
使用first()
代替get()
,因此不会抛出任何异常:
管理器:
class CustomerReferralManager(models.Manager):
def get_referral(self, mobile_number, campaign):
return self.objects.filter(mobile=mobile_number).first()
方法:
referral = CustomerReferral.objects.get_referral(mobile_number=mobile, campaign=campaign)
if referral:
referral.complete_referral()