django 意外访问一对一键调用 __setattr__

django accessing one-to-one key calls __setattr__ unexpectedly

我有一个 Django 模型,包括两个模型 classes(UserProfile 和 UserNotification)。每个配置文件都有一个可选的 last_notification。这是 models.py 中定义的 class 字段:

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 class 中的所有字段调用。那不应该发生?我对吗?知道为什么会这样吗?

我确定那里调用了 setattr

调用它是因为访问 profile.last_notif 的行为从数据库中加载了 UserNotification 对象,因为它之前没有加载过。这样做显然需要用数据库中的相关值设置实例的所有字段。