2014-11-21 56 views
24

我在我的模型的方法has_related_object,需要檢查是否有相關的對象存在Django的檢查,如果相關對象存在錯誤:RelatedObjectDoesNotExist

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

    def has_related_object(self): 
     return (self.customers is not None) and (self.car is not None) 


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

但我得到的錯誤:

Business.has_related_object()

RelatedObjectDoesNotExist: Business has no customer.

回答

32

編輯: mrts下面的答案是更好的。

這是因爲ORM必須前往數據庫檢查是否存在customer。由於它不存在,它引發了一個例外。

你必須改變你的方法如下:

def has_related_object(self): 
    has_customer = False 
    try: 
     has_customer = (self.customers is not None) 
    except Customer.DoesNotExist: 
     pass 
    return has_customer and (self.car is not None) 

我不知道跟self.car的情況,所以我要把它留給你是否需要它來調整它。

附註: 如果你在一個模型上使用了ForeignKeyField或OneToOneField,你可以做以下操作作爲避免數據庫查詢的快捷方式。

def has_business(self): 
    return self.business_id is not None 
+1

注意,根據DOC(https://docs.djangoproject.com/en/1.9/ref/models/fields/ #database-representation)「,」除非你編寫自定義SQL,否則你的代碼不應該處理數據庫的列名,你總是會處理模型對象的字段名。「 – 2016-01-08 14:19:38

+0

這種方法比其他答案快,因爲它不需要與數據庫交談。 – Dan 2017-06-07 09:09:16

58

使用hasattr(self, 'customers')避免異常檢查爲recommended in Django docs

def has_related_object(self): 
    return hasattr(self, 'customers') and self.car is not None 
+3

應該接受答案。 – 2017-02-17 19:52:02

+0

同意@iYalovoi – potatoes 2017-09-26 11:43:32