2016-08-07 20 views
0

我有一個包含兩個模型類(UserProfile和UserNotification)的django模型。每個配置文件都有可選的last_notification。以下是在models.py中定義的類字段:django訪問一對一按鍵調用__setattr__意外

class UserProfile(models.Model): 
    last_notif = models.OneToOneField('UserNotification', null=True, blank=True, default=None, 
             on_delete=models.SET_DEFAULT) 

class UserNotification(models.Model): 
    shown = models.BooleanField(default=False) 

    def __setattr__(self, key, value): 
     super(UserNotification, self).__setattr__(key, value) 
     print("SET ATTR", key, value) 

我有這個context-processor功能:

def process_notifications(request): 
    if request.user.is_authenticated(): 
     profile = UserProfile.objects.get(...) 
     notif = profile.last_notif 

當process_notifications最後一行被調​​用時,UserNotification我重寫SETATTR方法被調用用於UserNotification類中的所有字段。這不應該發生?我對嗎?任何想法爲什麼會發生?

我確定setattr在那裏被調用。

回答

0

這是因爲訪問profile.last_notif的行爲從數據庫加載UserNotification對象,因爲它以前沒有加載過。這顯然要求實例的所有字段都使用db中的相關值進行設置。

+0

謝謝丹尼爾。我在調試模式下檢查過,你是正確的。它通過__setattr __()重新生成對象並設置屬性。 – user24353