ListCreateAPIView POST带有序列化程序中未注释模型的带注释字段

时间:2018-11-05 02:44:16

标签: django django-rest-framework

我正在构建一个简单的预算应用程序来学习Django&React。我已经使用DRF构建了一个API,以创建数据库并从中获取事务。目前,当我执行GET时,我正在即时计算总的运行余额。这一直很好,但是当我执行POST时,我收到一个错误消息,要求我提供动态平衡字段,因为该字段位于序列化程序中。我该如何解决?

views.py

class CreateView(generics.ListCreateAPIView):
    """This class defines the GET & POST behavior of the rest api."""

    queryset = Transaction.objects.all()

    # This is the balance that's calculated on the fly
    queryset_with_balance = queryset.annotate(balance=Window(Sum('amount'),
                                                             order_by=F('created_time').asc())).all().order_by('-created_time')

    serializer_class = TransactionSerializer

    def perform_create(self, serializer):
        """Save the post data when creating a new transaction."""
        serializer.save()

    def get_queryset(self):
        return self.queryset_with_balance

serializers.py

class TransactionSerializer(serializers.ModelSerializer):
    balance = serializers.DecimalField(decimal_places=2, max_digits=19)

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = Transaction
        fields = ('id', 'date', 'payee', 'category',
                  'amount', 'balance', 'created_time', 'modified_time')

models.py

class Transaction(models.Model):
    date = models.DateField()
    payee = models.CharField(max_length=256)
    category = models.CharField(max_length=256)
    amount = MoneyField(max_digits=19,
                        decimal_places=2,
                        default_currency='USD')    
    created_time = models.DateTimeField(auto_now_add=True)
    modified_time = models.DateTimeField(auto_now=True)

1 个答案:

答案 0 :(得分:1)

balance字段设置为 read_only ,如下所示,

class TransactionSerializer(serializers.ModelSerializer):
    balance = serializers.DecimalField(decimal_places=2, max_digits=19, read_only=True)
    # your code



来自DRF doc

  

只读字段包含在API输出中,但在创建或更新操作期间不应包含在输入中