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在那裏被調用。
謝謝丹尼爾。我在調試模式下檢查過,你是正確的。它通過__setattr __()重新生成對象並設置屬性。 – user24353