我在这里的模型中有两个字段:
is_active = models.BooleanField(default=False)
active_from = models.DateTimeField(blank=True)
当
is_active
设置为 True
, 我要 active_from
更新到当前日期时间。我该怎么做?如果在一个领域也有一种更清洁的方法,我愿意接受替代方案。
谢谢!
编辑:我想在模型中包含它以保持封装。这将是 API 的一部分。
最佳答案
一种方法是定义一个 save()
您的自定义模型上的方法在 is_active
中寻找更改.没有简单的方法可以实现这一点:您需要手动保存 is_active
的值的先前状态。通过定义自定义 __init__
-方法。它可能看起来像这样:
class MyModel(models.Model):
is_active = models.BooleanField(default=False)
active_from = models.DateTimeField(blank=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__is_active = self.active
def save(self, *args, **kwargs):
if self.is_active and not self.__is_active:
self.active_from = datetime.now()
super().save(*args, **kwargs)
This question有一些答案可能会有所帮助。
关于django - 当更新同一模型中的另一个特定字段时,如何更新 Django models.DateTimeField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37867447/