10

I am building an app using Django 1.10 as backend. Is it possible to set a model field's default relative to another model from the same instance?

I specifically need to set second_visit's default to be 3 weeks after the first_visit

class SomeModel(models.Model): 
    first_visit = models.DateField()
    second_visit = models.DateField(default= second_visit_default)

    def second_visit_default(self):
        # Set second_visit to 3 weeks after first_visit
Krish Munot
  • 1,043
  • 1
  • 18
  • 28
Vingtoft
  • 11,443
  • 17
  • 68
  • 114

2 Answers2

12

You cannot assign a default value on a field dependent on another before having a model instance. To achieve the same you can override the save() method of the model:

class SomeModel(models.Model):

    ...

    def save(self, *args, **kwargs):
        self.second_visit = self.first_visit + datetime.timedelta(weeks=3)
        super().save(*args, **kwargs)
Evans Murithi
  • 3,067
  • 1
  • 20
  • 26
  • 4
    Warning: this is not the same as having a default. This will break any subsequent saves of the model where the user will actually want to set an explicit value in that field. – BjornW Aug 06 '20 at 09:28
2

You can override save or usepre_save

from django.db.models.signals import pre_save
from django.dispatch import receiver


@receiver(pre_save, sender=SomeModel)
def my_handler(sender, instance, **kwargs):
    instance.second_visit = # Set second_visit to 3 weeks after instance.first_visit
itzMEonTV
  • 18,806
  • 3
  • 37
  • 48