Borealis
Borealis

Reputation: 1137

Django: how to change the value of a field one changing another?

I have 2 fields in a model I need that when I change the value of a field to calculate the other

Example:

    Date_mission1_equipe=models.DateField (null=True,blank=True,max_length=200)
Date_mission2_equipe=models.DateField (null=True,blank=True,max_length=200)

for example if i choose 01/01/2019 for Date_mission1_equipe automatically Date_mission2_equipe should be 02/01/2019

Upvotes: 1

Views: 1463

Answers (2)

djangomachine
djangomachine

Reputation: 709

It is often recommended not to store calculated values like this in the database. Instead, just perform the calcaultion when you will need it.

from datetime import timedelta

class Mission(models.Model):
    date_mission1_equipe = models.DateField(null=True, blank=True)

    @property
    def date_mission2_equipe(self):
        return self.date_mission1_equipe + timedelta(days=1)

You can now do something like this:

first_mission = Mission.objects.get(id=1)
first_mission.date_mission1_equipe
<01/01/2019>
first_mission.date_mission2_equipe
<02/01/2019>

That's just an example. The date would probably need to be formatted for your needs, and will not automatically output in the format I put above.

Also, you do not need max_length on a DateField. It makes no sense for this field type.

Upvotes: 2

rob
rob

Reputation: 2144

There are few ways to handle this. You could override the model save method. Or perhaps the cleanest is to use a pre_save signal, as shown below.

from django.db.models.signals import pre_save

def change_date(sender, instance, **kwargs):
    my_object = MyModel.objects.get(id=instance.id)
    if instance.Date_mission1_equipe:
        a.Date_mission2_equipe = ...

pre_save.connect(change_date, sender=MyModel) 

Upvotes: 4

Related Questions