当 django 模型与此逻辑勺中同一模型的另一个字段 link 时,无法编辑布尔字段?

can't edit Boolean field on django model when it is link with another field from the same model within this logic scoop?

我正在开发 django v4.*,我遇到了一个问题,我需要在 is_published is ticked

时自动填充字段 publish_date
import datetime
class Article(models.Model):
     .......
     is_published = models.BooleanField(default=False)
     publish_date = models.DateTimeField(blank=True, null=True)
     .......
     def save(self, *args, **kwargs):
        if self.is_published:
           self.publish_date = datetime.datetime.now()
           super().save(*args, **kwargs)

这成功了,但问题是我无法再编辑 is_published 字段, 当我勾选它(使其为真)时,即使我尝试将其更改为取消勾选,它也保持为真

您的保存操作现在是您的 if: 语句的一部分。将其降低一个缩进级别,以便它始终结束函数

 def save(self, *args, **kwargs):
    if self.is_published:
       self.publish_date = datetime.datetime.now()
    super().save(*args, **kwargs)