简体   繁体   中英

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

like i say in the title i need to fill automatically a field of my Django Model specifically a DateField adding X number of days that i specify in the same model form.

In my case i need to add the number of days taht i put in "total_days" to the date that i use in the field "start_day" and save the result on "end_day".

Here is the model:

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

Well i try using "timedelta" but i can't use the start_day field because not detect this like a integer. And timedelta need a integer parameter.

Any Idea about how i can do this???

Now i'm doing this directly on the view and send the result on the context to the template. But the user needs to keep this from the first into the database.

Thanks very much!

You can create get_end_date function and to which you can pass the start date as parameter. according to your coding convenience.

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>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM