我有一个django模型,包括两个模型类(UserProfile和UserNotification)。每个配置文件都有一个可选的last_notification。下面是在models.py中定义的类字段:
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)我有一个上下文处理器函数:
def process_notifications(request):
if request.user.is_authenticated():
profile = UserProfile.objects.get(...)
notif = profile.last_notif当调用process_notifications中的最后一行时,对类中的所有字段调用UserNotification中覆盖的setattr方法。这不应该发生吗?我说的对吗?知道为什么会这样吗?
我确信setattr在那里被称为。
发布于 2016-08-07 09:36:09
之所以调用它,是因为访问profile.last_notif的行为从数据库加载UserNotification对象,因为它以前没有加载过。这样做显然需要使用来自db的相关值来设置实例的所有字段。
https://stackoverflow.com/questions/38812596
复制相似问题