我的模型上有自定义的.save方法。该模型具有for (let i = 0; i < 10; i++) {
var userobj1 = {};
userobj1.name = 'joe';
userobj1.age = '29'
var newuser = new User(userobj1);
userobj1.save(function (err, user) {
if (err) console.log(err)
return user
}).then(function (user) {
console.log(user)
})
}
和start_date
值。如果这些值之间的差异超过14天,它应该在保存时复制/克隆(而不是保存)。
您可能已经看到了问题:无限递归。如果克隆自行保存,则值仍将相差14天,整个复制过程将重新开始。
因此,我想在其.save参数中传递这些副本last_edited
参数,以防止它们自己触发复制过程。
为此,我编写了以下代码:
'copy'
但是,出于某种原因def save(self, *args, **kwargs):
#check if a submission is older than the 'create a new one' threshold
#Create a new one if that is the case
delta = self.last_edited - self.start_date
print(args)
print(kwargs)
if 'copy' in kwargs or 'copy' not in args:
print('cloning!')
if delta.days >= 14:
clone = self
clone.pk = None
clone.save('copy')
super(AssessmentSubmission, self).save(*args, **kwargs)
没有将'copy'变量传递给.save方法。我甚至添加了一些print语句来打印所有clone.save(copy)
和args
个参数,但两者都返回空列表/ dicts。
有谁知道我做错了什么?
答案 0 :(得分:1)
为什么不在模型中设置标志字段?比*kwargs
和**args
更清洁。类似的东西:
class AssessmentSubmission(models.Model):
'''
Your other fields here
'''
flag_field = models.IntegerField(default=0,blank=True,null=True)
def save(self):
#check if a submission is older than the 'create a new one' threshold
#Create a new one if that is the case
delta = self.last_edited - self.start_date
print(args)
print(kwargs)
if not self.flag_field:
print('cloning!')
if delta.days >= 14:
clone = self
clone.pk = None
clone.flag_field = 1
clone.save('copy')
super(AssessmentSubmission, self).save()
希望这有帮助!