Home > OS >  Django Calculated fields Save()
Django Calculated fields Save()

Time:11-05

This is very basic, but I'm having trouble finding the correct way to do this. I would like to have fields that are calculated and saved into the database. In the example, cHpd,cMpd and cBph are all fields that are calculated in the calc_rates function. I am piecing together how to do this.

class Route(models.Model):
    rtNumber = models.CharField(max_length = 5)
    rtState = models.CharField(max_length = 2)
    rtOffice = models.CharField(max_length = 255)
    #stDate = models.DateField(blank=True)
    #edDate = models.DateField(blank=True)
    llcName = models.CharField(max_length =255)
    boxes = models.IntegerField(null=True)
    miles = models.IntegerField(null=True)
    hours = models.IntegerField(null=True)
    wrkDays = models.IntegerField(null=True)
    activeCont= models.BooleanField(default=None)
    contRate = models.IntegerField(null=True)
    cHpd = models.IntegerField(null=True)
    cMpd = models.IntegerField(null=True)
    cBph = models.IntegerField(null=True)


    @property
    def calc_rates(self):
        hpd = self.hours / self.wrkDays
        mpd = self.miles / self.wrkDays
        bph = self.boxes / hpd

        self.cHpd = hpd
        self.cMpd = mpd
        self.cBph = bhp

        super(Route, self).save()

CodePudding user response:

You need a Model property for each calculated field, like so:

@property
def hpd(self):
    return self.hours / self.wrkDays

@property
def mpd(self):
    return self.miles / self.wrkDays

@property
def bph(self):
    return self.boxes / self.hpd

CodePudding user response:

If you want to save it in the database you can use signals. Then it will be calculated everytime you run .save() on the model.

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

@receiver(pre_save, sender=Route)
def my_callback(sender, instance, *args, **kwargs):
    instance.hpd = instance.hours / instance.wrkDays

But, there's really no point in saving it in the database in my opinion, I would remove the fields cHpd etc. and use the solution that Lewis provided.

  • Related