如何使用同一模型的 IntegerField 将天数添加到 Django 模型的日期时间字段?

How can i add days to a datetime field on a django model, using a IntegerField of the same model?

就像我在标题中所说的那样,我需要自动填写我的 Django 模型的一个字段,特别是 DateField 添加我在同一模型表单中指定的 X 天数。

在我的例子中,我需要将我在 "total_days" 中输入的天数添加到我在字段 "start_day" 中使用的日期,并将结果保存在 "end_day" 中。

这是模型:

class Certificate(models.Model):

    employee = models.ForeignKey(Employee)
    license_type = models.IntegerField(choices=LICENSE_TYPES, default=1)
    disease_type = models.IntegerField(choices=DESEASE_TYPES, blank=True, null=True)
    total_days = models.PositiveIntegerField()
    extra_days = models.PositiveIntegerField(Default=0)
    start_day = models.DateField()
    end_day = models.DateField(, editable=False)
    doctor = models.ForeignKey(Doctor)
    diagnostic = models.CharField(max_length=150)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(User, related_name='certificates_created_by', editable=False)
    modified_by = models.ForeignKey(User, related_name='certificates_modified_by', editable=False, blank=True, null=True)


    class Meta:
        verbose_name = "certificado"
        verbose_name_plural = "certificados"

    def __str__(self):
        pass

好吧,我尝试使用 "timedelta",但我无法使用 start_day 字段,因为无法将其检测为整数。而timedelta需要一个整型参数。

知道我该怎么做吗???

现在我直接在视图上执行此操作,并将上下文中的结果发送到模板。但是用户需要把这个从头存入数据库。

非常感谢!

您可以创建 get_end_date 函数并将开始日期作为参数传递给该函数。根据您的编码方便。

from datetime import datetime, timedelta
start_date = datetime.strptime(start_day, "FORMAT") #start_day should be from your model and FORMAT as it is
end_day = start_date + timedelta(days=no_of_days_to_add)
end_date = end_day.strftime(end_day, <FORMAT>)