哪个更好,检查管理器或方法中是否存在对象?
Which is better practice, checking object exists in Manager or Method?
在 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
使用 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()
在 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
使用 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()