如何修改get_queryset结果值

时间:2018-03-26 12:39:55

标签: django python-3.x django-models django-rest-framework

我正在尝试修改我的get_queryset结果

这是我的过滤器,视图和序列化程序

view.py

 class AccountDetailFilter(filters.FilterSet):
        product_key = filters.CharFilter(name='product__product_name')
        account_name = filters.AllValuesFilter(name='account__account_key')
        service_provider_name = filters.CharFilter(name='product__service_provider__service_provider_name', )
        allocation_key = filters.CharFilter(name='account__account_allocation__allocation_key')

        class Meta:
            model = BillingLine
            fields = ('product_key', 'account_name', 'service_provider_name', 'allocation_key')

class AccountDetailList(generics.ListAPIView):
    serializer_class = BillingSerializer
    filter_backends = (DjangoFilterBackend,)
    filter_class = AccountDetailFilter


    def get_queryset(self):
        now = datetime.datetime.now()
        start_date = self.kwargs.get('start_date_time', now)
        end_date = self.kwargs.get('end_date_time', now)
        serializer = BillingSerializer(data={'start_date': start_date, 'end_date': end_date})
        serializer.is_valid(raise_exception=True)
        queryset = BillingLine.objects.select_related().filter(start_date__gte=start_date, end_date__lte=end_date)
        queryset =  queryset.order_by('-id')
        print(queryset.count())
        return queryset

Serializers.py

class BillingSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    start_date = serializers.DateTimeField()
    end_date = serializers.DateTimeField()
    account_key = serializers.CharField(source='account_id',required=False)
    product_key = serializers.CharField(source='product_id',required=False)
    total_amount = serializers.FloatField(required=False)

检索结果(即get_queryset)后,我需要修改/添加结果中的数据。有没有办法做到这一点。

我们也可以从结果查询集中获取序列化程序的其他字段值。因为queryset = BillingLine.objects.select_related().filter(start_date__gte=start_date, end_date__lte=end_date)返回的几乎所有数据(特别是产品名称来自产品表)

1 个答案:

答案 0 :(得分:1)

覆盖get_queryset()方法将完美地满足您的目的。

例如: 在views.py

class AccountDetailList(generics.ListAPIView):
    serializer_class = BillingSerializer
    filter_backends = (DjangoFilterBackend,)
    filter_class = AccountDetailFilter
    def get_queryset(self):
        qs = YourModel.objects.filter(**filter_parameter)
        return qs

    def list(self):
        try:
            queryset = self.get_queryset()
            serialize_value = YourSerializers(queryset,many=True,context={'request': self.request}).data
            #Here in "serialize_value" you can append your data as much as you wish
            return_val = {
                'modified_serialize_value': serialize_value
            }    
            return Response(return_val, status=status.HTTP_200_OK, content_type='application/json')
        except Exception as E:
            return Response({'error': str(E)}, status=status.HTTP_408_REQUEST_TIMEOUT, content_type='application/json')

我希望这会有所帮助。