哪种更好的做法,检查对象是否存在于Manager或Method中?

时间:2015-01-06 12:06:57

标签: python django

在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         

1 个答案:

答案 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()