在保存Django模型之前检索属性

时间:2016-06-24 20:20:39

标签: django django-models

我遇到了一个问题,在保存之前我无法检索实例的值。它将返回save()方法中的更新值。此外,我无法存储在__init__中,因为它运行的查询太多。我想仅在用户保存该实例时运行查询

以下是我简化的模型:

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

class Groups(models.Model):
    name = models.CharField(max_length=100)
    user = models.ManyToManyField(Users)
    '''def __init__(self, *args, **kwargs):
        super(Groups, self).__init__(*args, **kwargs)
        #store original values
        for field in Groups._meta.get_fields():
            f = field
            if not f.many_to_many:
                setattr(self, '__original_%s' % f.name, getattr(self, f.name))
            else:
                userlist = Users.objects.all().filter(groups__id=self.pk)
                setattr(self, '__original_userlist', set(userlist)) #set() to force lazy query and get original value'''

    #function trying to reproduce __init__
    def store(self):
        for field in Groups._meta.get_fields():
            f = field
            if not f.many_to_many:
                setattr(self, '__original_%s' % f.name, getattr(self, f.name))
            else:
                userlist = Users.objects.all().filter(groups__id=self.pk)
                setattr(self, '__original_userlist', set(userlist)) #set() to force lazy query


    def save(self, *args, **kwargs):
       self.store()
       print(getattr(self, '__original_userlist')) #return the list with users
       super(Groups, self).save(*args, **kwargs)
       print(getattr(self, '__original_userlist')) #return the list with users

我不确定最好的方法,因为我必须进行查询。我这样做是为了比较旧值和新值,然后我可以存储日志文件中不同的值。

1 个答案:

答案 0 :(得分:0)

我通过在super()调用之前再次查询实例并使用该对象来解决此问题。它返回了所有字段的旧值,但我还需要检查m2m字段,它显示为users.None

要获得m2m的值,我必须使用m2m_change信号!