Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models: Set default relative to another field

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
like image 585
Vingtoft Avatar asked Dec 27 '16 10:12

Vingtoft


2 Answers

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)
like image 172
Evans Murithi Avatar answered Nov 03 '22 13:11

Evans Murithi


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
like image 2
itzMEonTV Avatar answered Nov 03 '22 13:11

itzMEonTV