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
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With