我有一个模型和模型定义如下
class Article(models.Model):
is_draft = models.BooleanField(default=True)
date_published = models.DateTimeField(editable=False, blank=True, null=True)
def save(self, *args, **kwargs):
if (self.is_draft == False) and (self.date_published == None):
self.date_published = datetime.now()
super().__init__(*args, **kwargs)
class ArticleForm(models.ModelForm):
class Meta:
fields = ['is_draft']
def save(self, force_insert=False, force_update=False, commit=True):
article = Article(**self.cleaned_data)
article.save()
奇怪的是,当我将自定义保存方法添加到模型时,ArticleForm的save方法的参数将传递给它。也就是说,force_insert = False,force_update = False也会传递给Article save方法。为什么会这样?
答案 0 :(得分:2)
ArticleForm.save()
参数未在Article.save()
方法中使用,除非您明确传递它们。 force_insert
和force_update
是默认的Model.save()
参数,如Django model save documentation中所述。它们的值取决于您如何调用Model.save()
方法。
此外,您的文章保存方法应如下所示:
class Article(models.Model):
...
def save(self, *args, **kwargs):
if (self.is_draft == False) and (self.date_published == None):
self.date_published = datetime.now()
super(Article, self).save(*args, **kwargs)