如何在GET,POST请求中验证参数?

时间:2019-11-19 13:21:34

标签: python api validation serialization django-rest-framework

我有视图和序列化器。我如何在GET api/transaction?date=2019-11-05和POST请求中验证参数。 视图*

class TransactionViewSet(viewsets.ModelViewSet):

    queryset = Transaction.objects.all()
    serializer_class = TransactionSerializer
    pagination_class = LimitOffsetPagination

序列化器

class TransactionSerializer(serializers.Serializer):

    transfers = TransferSerializer(many=True)
    partner_transaction = PartnerTransactionDataSerializer(many=True)
    purchase_transaction = PurchaseTransactionDataSerializer(many=True)

    class Meta:
        model = Transaction
        fields = (
            'created_at',
            'transaction_type_id',
            'transfers',
            'partner_transaction',
            'purchase_transaction'
        )

1 个答案:

答案 0 :(得分:2)

您可以在视图中覆盖queryset方法

class TransactionViewSet(viewsets.ModelViewSet):

    queryset = Transaction.objects.all()
    serializer_class = TransactionSerializer
    pagination_class = LimitOffsetPagination

    def get_queryset(self):
        date = self.request.GET.get('date')
        return super().get_queryset().filter(created_at=date)