如何在Djano RestFrameW中进行简单计算

2024-04-23 15:15:06 发布

您现在位置:Python中文网/ 问答频道 /正文

型号.py

class SaleE(models.Model):
  qty = models.CharField(max_length=250)
  rate = models.CharField(max_length=250)
  tax = models.CharField(max_length=250,null="True")
  slno= models.CharField(max_length=250)
  ptype =models.CharField(max_length=250)
  pdiscription = models.CharField(max_length=250)
  pname = models.CharField(max_length=250)
  amount = models.CharField(max_length=10)

序列化程序.py

class SaleESerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = SaleE
        fields = ('id','slno','pname','ptype','pdiscription','qty','rate','tax','amount')

这里我想做一个简单的计算为例 如果我给一个200的量,加上结果应该像400在后端本身,它应该计算,所以如何做到这一点。你知道吗


Tags: pyratemodelsamountlengthmaxclassqty
1条回答
网友
1楼 · 发布于 2024-04-23 15:15:06

您可以通过多种方式进行:重写clean方法、写入信号或在序列化程序中重写

覆盖模型的clean方法

class SaleE(models.Model):
    ....
    your model fields
    ....

    def clean(self):
        # perform any calculation you want to perform at here..
        # self: model instance of your current record
        self.amount = self.amount * 2

在clean方法中,您可以在保存前计算或修改实例。你知道吗

写入信号

@receiver(pre_save, sender=SaleE) # pre_save is signal type which will called before save method
def create_firebase_account(sender, instance, created, *args, **kwargs):
    """
    sender: sender model from which you'll receive signal from
    instance: model instance(record) which is saved (it will be instance of sender model)
    """
    if created:  # use this condition if you want to alter amount only at creation time
        instance.amount = instance.amount * 2

如果您只希望在保存前修改字段值,而不是从shell或任何其他视图保存,则可以重写视图中的perform_create方法或序列化程序中的create方法

当您编写信号时,每当为模型实例调用save()方法时,它都将执行计算,但如果您在序列化程序中重写,它将只能在您尝试仅通过API更新/创建模型实例时进行计算

相关问题 更多 >