2016-08-07 77 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