[英]Auto calculation on a field in a model in Django RESTframework
So I have a model which has an attribute to be auto calculated when the api receives a POST request. 所以我有一个模型,该模型的属性在api收到POST请求时自动计算。 The model is a bill model where the totalpayment is calculated on numberOfHours * paymentRate. 该模型是账单模型,其中总付款额是根据numberOfHours * paymentRate计算的。 Django does not allow me to do so by setting default value. Django不允许我通过设置默认值来这样做。 Is there a way to do this? 有没有办法做到这一点?
Model 模型
class Bill(models.Model):
billID = models.AutoField(primary_key=True)
bill_dt = models.DateField()
hours = models.FloatField()
workAssignmentID_fk = models.ForeignKey(WorkAssignment, null=True, default=None)
totalPayment = models.FloatField(default=0)
def __unicode__(self):
return u'%s' % (self.bill_dt)
def __str__(self):
return u'%s' % (self.bill_dt)
Serializer 串行
class ReadBillSerializer(serializers.HyperlinkedModelSerializer):
workAssignmentID_fk = ReadWorkAssignmentSerializer()
class Meta:
model = Bill
fields = ('url', 'bill_dt', 'hours', 'workAssignmentID_fk', 'totalPayment')
class WriteBillSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Bill
fields = ('url', 'bill_dt', 'hours', 'workAssignmentID_fk', 'totalPayment')
View 视图
class BillViewSet(viewsets.ModelViewSet):
queryset = Bill.objects.all()
def get_serializer_class(self, *args, **kwargs):
if self.request.method == 'POST' or self.request.method == 'PUT':
return WriteBillSerializer
return ReadBillSerializer
In the model Bill, I want totalPayment = hours * workAssignmentID_fk.paymentRate. 在模型Bill中,我希望totalPayment =小时* workAssignmentID_fk.paymentRate。
paymentRate is an attribute in the workAssignmentID_fk. paymentRate是workAssignmentID_fk中的一个属性。
You can override perform_create()
function in your view and pass the value of totalPayment
to the save()
method of serializer. 您可以在视图中覆盖perform_create()
函数,并将totalPayment
的值totalPayment
给序列化器的save()
方法。
perform_create()
is called when saving a new object instance. 保存新的对象实例时,将调用perform_create()
。 You can use this object creation hook. 您可以使用此对象创建挂钩。
class BillViewSet(viewsets.ModelViewSet):
queryset = Bill.objects.all()
def get_serializer_class(self, *args, **kwargs):
if self.request.method == 'POST' or self.request.method == 'PUT':
return WriteBillSerializer
return ReadBillSerializer
def perform_create(self, serializer):
hours = serializer.validated_data['hours'] # get the value of hours
work_assignment_object = <get_the_workAssignmentID_fk_object_from_passed_url>
payment_rate = work_assignment_object.paymentRate # get the value of 'paymentRate' from work assignment object
total_payment = hours*payment_rate # calculate value of total payment
serializer.save(total_payment=total_payment, workAssignmentID_fk=work_assignment_object) # pass the value of total payment to be saved and the work assignment object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.