使用DRF分页与ListSerializer导致异常

时间:2015-11-14 10:28:47

标签: python django pagination django-rest-framework

问题是当我在ListSerializer上使用paginationDRF时出现异常。

我有以下代码

  

serializers.py

class IsDeletedFilteredListSerializer(serializers.ListSerializer):
    def to_representation(self, data):
        data = data.filter(is_deleted=False)
        return super(IsDeletedFilteredListSerializer, self).to_representation(data)


class GallerySerializer(serializers.ModelSerializer):
    class Meta:
        model = Gallery
        list_serializer_class = IsDeletedFilteredListSerializer  


class ProductSerializer(serializers.ModelSerializer):
    galleries = GallerySerializer(many=True, read_only=True)

    class Meta:
        model = Product
        list_serializer_class = IsDeletedFilteredListSerializer
  

views.py

class ProductView(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    model = Product
    http_method_names = ['get', 'post', 'head','patch']

    paginate_by = 20


class GalleryView(viewsets.ModelViewSet):
    serializer_class = GallerySerializer
    model = Gallery
    filter_fields = ('product',)
    http_method_names = ['get', 'post', 'head','patch']

当我尝试获得产品时:

  

'list'对象没有属性'filter'

但当我删除paginate_by = 20时,一切正常。 这似乎在ListFilter之前发生分页并将查询集转换为列表。

因为我使用Django Admin interface,所以更改ObjectManager是不合适的,因为我在视图上使用nested serializers重写查询集也不起作用(过滤器产品和嵌套库不会过滤)。

  

我在Python 3.4上使用Django 1.8.6和DRF 3.1.3

1 个答案:

答案 0 :(得分:1)

您可以通过过滤Products中的get_queryset并使用IsDeletedFilteredListSerializer仅过滤galleries来解决此问题。

你可以这样做:

class ProductView(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    http_method_names = ['get', 'post', 'head','patch']
    paginate_by = 20

    def get_queryset(self):
        return Product.objects.filter(is_deleted=False)

并在ProductSerializer中删除序列化程序Meta类中的list_serializer_class选项。

class ProductSerializer(serializers.ModelSerializer):
    galleries = GallerySerializer(many=True, read_only=True)

    class Meta:
        model = Product

这样您就可以过滤productsgallaries