问题是当我在ListSerializer
上使用pagination
并DRF
时出现异常。
我有以下代码
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
答案 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
这样您就可以过滤products
和gallaries