简体   繁体   中英

Django: Operations on different fields of two different models

here two classes are defined, i would like to do some calculations on different field of both models.

class A(models.Model):
    newspaper = models.CharField(max_length=50)
    language = models.CharField(max_length=50, choices=Language)
    wh_price = models.DecimalField(max_digits=6,decimal_places=2)
    sa_price=models.DecimalField(max_digits=6,decimal_places=2)

class B(models.Model):
    added_date = models.DateField(max_length=32,auto_now_add=True)
    newspaper = models.ForeignKey(Newspaper,on_delete=models.CASCADE)
    qty=models.IntegerField(default=0)
    qty_return =models.IntegerField(default=0)
    total = models.DecimalField(max_digits=6,decimal_places=2)

total (from B) = wh_price (from A) * qty (from B)

you can overide the save function of class b as following:

class Intake(models.Model):
    # your fields..
    # below is the save function which we are overriding
    save(self, *args, **kwargs):
        self.total = self.newspaper.wh_price * self.qty
        super(Intake, self).save(*args, **kwargs)

this will serve the purpose as far as i understand the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM