如何在Djano RestFrameWork中进行简单的计算

时间:2018-04-10 04:46:14

标签: python django django-models django-rest-framework django-views

model.py

public function getContacts($limit, $start, $search)
{
  $this->db->select('*');
  $this->db->from('contact');
  if (!empty($search)) {
    $this->db->like('name', $search);
    $this->db->or_like('last_name', $search);
    $this->db->or_like('phone_number', $search);
    $this->db->or_like('created_at', $search);
    $this->db->or_like('note', $search);
  }

  $this->db->where(array('user_id' => 3));
  $this->db->limit($limit, $start);
  $query = $this->db->get();
  return $query->result_array();
}

Serializer.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)

这里我想对一个例子做一个简单的计算 如果我给予金额200另外结果应该像后端400那样它应该计算如何做到这一点。

1 个答案:

答案 0 :(得分:0)

您可以通过多种方式继续:通过覆盖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

如果您希望仅在保存API调用之前修改字段值,而不是来自shell或任何其他视图,则可以覆盖视图中的perform_create方法或序列化程序中的create方法

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