2013-04-17 67 views
1

有這樣的代碼:檢查外鍵對象設置

class SomeModel(models.Model): 
    pass 

class OtherModel(models.Model): 
    some_model = models.ForeignKey(SomeModel) 

om = OtherModel() 
if om.some_model: 
    pass 

引發的異常是:

models.DoesNotExist 

有一些很好的辦法來檢查,如果在國外的關鍵對象設置,而不是嘗試...除了或hasattr?

回答

1
om = OtherModel() 

'Just'實例化一個python類。使用模型的經理在訪問屬性之前保存的關係,或設置字段設置爲null =真

om = OtherModel.objects.create() 

看一看在official manager documentation