Django - Update model field based on another field

后端 未结 2 1000
半阙折子戏
半阙折子戏 2021-01-13 09:22

I am new to Django and Python and I want to do something I used to do very often in Java EE.

Consider the following model (only relevant classes):

cl         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-13 09:30

    See if this works for you. We override the save method and check if there is a pk. If the pk is None, we know that the SaleDetail is new. Then, we see if there is a unit_price. If there is not a unit_price, we set it to the Item.default_price.

    class Item(models.Model):
        name = models.CharField(max_length=40)
        default_price = models.DecimalField(max_digits=6, decimal_places=2, default=50)
    
        def __unicode__(self):
            return self.name
    
    
    class SaleDetail(models.Model):
        item = models.ForeignKey(Item)
        deposit = models.ForeignKey(Deposit)
        quantity = models.PositiveIntegerField()
        unit_price = models.DecimalField(max_digits=6, decimal_places=2)
        sale = models.ForeignKey(Sale)
    
        def save(self, *args, **kwargs):
            # Make sure this is the first save (pk should be None) and there is no unit_price set
            if self.pk is None and not self.unit_price:
                self.unit_price = self.item.default_price
            elif not self.unit_price:
                self.unit_price = self.item.default_price
    
            # Call the original save method
            super(SaleDetail, self).save(*args, **kwargs)
    

提交回复
热议问题