Django模型返回save()中的更新值,而不是M2M实例中的旧值

时间:2016-06-23 19:40:24

标签: django python-3.x django-models manytomanyfield

这是我的模特

class Userlist(models.Model):
    username = models.CharField(max_length=20)

class Mailinglist(models.Model):
    users = models.ManyToManyField(Userlist, blank=True)

    def __init__(self, *args, **kwargs):
        super(Mailinglist, self).__init__(*args, **kwargs)
        userlist = Userlist.objects.all().filter(mailinglist__id=self.pk)
        setattr(self, '__original_userlist', userlist)

    def log(self):
        userlist = Userlist.objects.filter(mailinglist__id=self.pk)
        original = getattr(self, '__original_userlist')
        print(userlist) #HERE1
        print(original) #HERE2

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        super(Mailinglist, self).save(force_insert, force_update, *args, **kwargs)
        self.log()

我正在尝试在我的邮件列表中添加或删除用户之前和之后获取值,但#HERE1 中的值相同(新值) #HERE2 即可。有什么想法,我怎么能得到旧的价值?

1 个答案:

答案 0 :(得分:0)

好的,我修好了。一旦真正需要,Django只会调用查询。 (懒惰查询?)

我所做的是强迫查询。

我将列表设为

def __init__(self, *args, **kwargs):
    super(Mailinglist, self).__init__(*args, **kwargs)
    userlist = Userlist.objects.all().filter(mailinglist__id=self.pk)
    setattr(self, '__original_userlist', set(userlist))

然后

def log(self):
    userlist = Userlist.objects.filter(mailinglist__id=self.pk)
    original = getattr(self, '__original_userlist')
    print(set(userlist)) #HERE1
    print(original) #HERE2

这样我甚至可以与

进行比较
diff = set_original - set_actual