Django - Update model field based on another field

后端 未结 2 981
半阙折子戏
半阙折子戏 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:52

    The "unit price" is a literally a function of two different fields. As such I would tend to write it like this:

    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()
        entered_unit_price = models.DecimalField(max_digits=6, decimal_places=2, default=None)
        sale = models.ForeignKey(Sale)
    
        @property
        def unit_price(self, value):
            if self.entered_unit_price is None:
                return self.item.default_price
            else:
                return self.entered_unit_price
    
        @unit_price.setter
        def unit_price(self, value):
            self.entered_unit_price = value
    

    Then use it like so:

    print(sd.unit_price)
    sd.unit_price = 500 
    sd.save()
    

提交回复
热议问题