缺少DRF中嵌套序列化程序的上下文

时间:2016-10-27 11:40:04

标签: python django serialization django-rest-framework

我遇到了一个奇怪的问题,其中一个序列化程序没有获取上下文而因此失败。

首先,在视图集中,我实现了一种列表方法,我根据一些依赖于模型中嵌套关系的标准来过滤订单。

class OrdersInAgendaViewSet(OrderMixin, viewsets.ReadOnlyModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderInAgendaSerializer
    permission_classes = (
        CanManageOrder,
    )

    def list(self, request):
        final_orders = set()
        qs = super(OrdersInAgendaViewSet, self).get_queryset()
        # Get only orders that have lines with products that have no rentals objects
        for order in qs:
            accommodations = False
            lines = order.lines.all()
            for line in lines:
                if line.product.rental:
                    accommodations = True
                    break
            if not accommodations:
                final_orders.add(order.pk)
        qs = qs.filter(pk__in=final_orders)
        serializer = self.serializer_class(qs, many=True)
        return Response(serializer.data)

现在是这个ViewSet的主要Serializer

class OrderInAgendaSerializer(serializers.ModelSerializer):
    lines = LineForAgendaSerializer(many=True, read_only=True)
    customer = CustomerInOrderSerializer(many=False, read_only=False)
    notes = OrderNoteSerializer(many=True, read_only=True)

    class Meta:
        model = Order
        fields = (
            'id',
            'date_placed',
            'status',
            'payment_status',
            'email_billing',
            'notes',
            'customer',
            'lines',
        )
        extra_kwargs = {'date_placed': {'required': False}}

正如您所看到的,我在这个上使用了3个以上的序列化程序,失败的是LineForAgendaSerializer:

class LineForAgendaSerializer(serializers.ModelSerializer):
    product = ProductForAgendaSerializer(many=False, read_only=True)
    customers = serializers.SerializerMethodField()

    class Meta:
        model = Line
        fields = (
            'starting_date',
            'ending_date',
            'product',
            'customers',
            'rents',
        )

    def get_customers(self, obj):
        customers = obj.customerinline_set.all()
        session_filter = self.context['request']\
            .query_params.get('session', None)

        if session_filter is not None:
            customers = customers.filter(
                sessions__id=session_filter).distinct()

        serializer = CustomerInLineForAgendaSerializer(customers, many=True, context=self.context)
        return serializer.data

违规行在get_customers方法中:

session_filter = self.context['request']\
            .query_params.get('session', None)

检查self.context是空的,所以我一直得到KeyError ......

如何将上下文传递给此序列化程序...是否应该从Viewset中完成(如果是这样?)或者从OrderInAgendaSerializer中完成(再次,如何?)

由于

1 个答案:

答案 0 :(得分:1)

是的,您应该从视图集传递上下文。

在这一行:

  

serializer = self.serializer_class(qs,many = True,context = { your context })

或者你可以使用应该工作的self.get_serializer()方法。