我正在努力向序列化程序类发送参数,我的代码如下:
models.py
class Transaction(models.Model):
owner = models.ForeignKey(User, on_delete=models.SET("DELETED"), related_name='transactions')
date = models.DateField(auto_now_add=True)
concept = models.CharField(max_length=100)
value = models.DecimalField(max_digits=10, decimal_places=2)
total = models.DecimalField(max_digits=10, decimal_places=2)
serializers.py
class TransactionSerializer(serializers.ModelSerializer):
total = serializers.ReadOnlyField(source='new_total')
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Transaction
fields = '__all__'
views.py
class TransactionHandler(viewsets.ModelViewSet):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
def perform_create(self, serializer):
last_transaction = Transaction.objects.latest('id')
new_total = last_transaction.total + Decimal(self.request.data['value'])
serializer.save(owner=self.request.user, new_total=new_total)
当在serializer.save()方法中时,只有owner参数才能正常工作,但是当我添加第二个参数时,一切都变得混乱
答案 0 :(得分:4)
您的序列化程序包含名为total
的字段,因此您需要将total
作为参数名称传递:
serializer.save(owner=self.request.user, total=new_total)