0
我遇到了一個問題,在保存之前我無法檢索到實例的值。它返回save()
方法中的更新值。此外,我無法存儲在__init__
中,因爲它運行的查詢太多。我要運行的查詢,只有當用戶保存該實例在保存之前在Django模型中檢索屬性
這裏是我的模型簡化:
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
我不知道最好的辦法的辦法,因爲我必須作出查詢。我這樣做來比較舊的和新的值,然後我可以在日誌文件中存儲不同的值。