2014-11-21 47 views
11

我不能看到得到這個工作...Django的RelatedObjectDoesNotExist錯誤

我在我的模型的方法has_related_object,需要檢查是否有相關的對象存在...

class Business(base): 
     name = models.CharField(max_length=100, blank=True, null=True) 


    def has_related_object(self): 
    has_customer = False 
    has_car = False 

    try: 
     has_customer = (self.customer is not None) 
    except Business.DoesNotExist: 
     pass 

    try: 
     has_car = (self.car.park is not None) 
    except Business.DoesNotExist: 
     pass 

    return has_customer and has_car 



class Customer(base): 
     name = models.CharField(max_length=100, blank=True, null=True) 
     person = models.OneToOneField('Business', related_name="customer") 

錯誤

相關對象DoesNotExist Business沒有客戶。

我需要檢查,如果存在這些相關的對象,但是從業務對象的方法

+0

你的問題是什麼?謝謝。 – alecxe 2014-11-21 15:38:40

+0

我需要檢查這些相關對象是否存在,但是來自業務對象方法 – Prometheus 2014-11-21 15:41:15

回答

12

內你捕捉except Business.DoesNotExist但是這不是多數民衆贊成拋出的異常。每this SO answer你想趕上一般DoesNotExist例外。

編輯:請參閱下面的註釋:實際例外被DoesNotExist捕獲,因爲它們繼承自DoesNotExist。你最好捕獲真正的異常,而不是抑制所涉及的模型中的任何和所有異常。

+1

爲了記錄,引發的異常在第一種情況下是'Customer.DoesNotExist',在第二種情況下是'Car.DoesNotExist'。 – 2014-11-21 16:03:58

+0

有沒有一個函數返回一個布爾值,我可以調用而不是捕獲錯誤?像'''model.DoesExists(other_model)''' – Jeremy 2014-12-18 05:52:36

+2

只是意識到,我可以打電話給hasattr就可以了......所以請不要介意 – Jeremy 2014-12-18 05:55:02