Home > Enterprise >  Saving previous date and adding new date in Django
Saving previous date and adding new date in Django

Time:10-05

I have been working on an application where user adds his tasks which he is supposed to perform, once the task is added he can update the progress.

In my model I have a date field, where user is supposed to enter the estimated completion date.

My task model

"""Creating KRA Based on Institutional Objectives"""
class KraBasedOnIo(models.Model):
    io = models.ForeignKey(InstitutionalObjectives, on_delete=models.CASCADE, related_name='kra_io')
    kra_title = models.CharField(max_length = 200)
    kra_description = models.TextField()
    kra_target = models.CharField(max_length=200)
    kra_added_date = models.DateTimeField(auto_now_add=True)
    estimated_date = models.????

While updating the progress, if the user wants to extend his timeline, I am looking for an option where I can save his current estimated completion date and add the new date also.

And when I am displaying his progress I want to show his defined completion date and also the extended completion date in the template.

I have tried a work around with model.JSONField() but couldn't reach there.

There is no ListField or DictionaryField so what could be a better solution for this?

CodePudding user response:

So I would use the library django-simple-history to keep track of the different updates of this field.

"""Creating KRA Based on Institutional Objectives"""
class KraBasedOnIo(models.Model):
    io = models.ForeignKey(InstitutionalObjectives, on_delete=models.CASCADE, related_name='kra_io')
    kra_title = models.CharField(max_length = 200)
    kra_description = models.TextField()
    kra_target = models.CharField(max_length=200)
    kra_added_date = models.DateTimeField(auto_now_add=True)
    estimated_date = models.DateTimeField(default=timezone.now)

    history = HistoricalRecords()

Then in you view, you can see the different version by doing :

for record in kra_based_on_info.history.all():
    print(record)

CodePudding user response:

Keep it simple and create two separated fields:

class KraBasedOnIo(models.Model):
    # ...
    estimated_completion_date = models.DateTimeField(null=True, blank=True)
    extended_completion_date = models.DateTimeField(null=True, blank=True)

If you need to keep track of all the completion date changes, I suggest you to create a new model

class CompletionDate(models.Model):
    # ...
    kra = models.ForeignKey(KraBasedOnIo, related_name='completion_dates', on_delete=models.CASCADE)
    estimated_date = models.DateTimeField(auto_now_add=True)

And then get the last completion date for a KraBasedOnIo instance like this:

my_last_completion_date = KraBasedOnIo.completion_dates.last()
  • Related