Reputation: 10931
The problem is when I'm using ListSerializer
with pagination
on DRF
I get exception.
I have the following codes
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']
When I try to get products:
'list' object has no attribute 'filter'
but when I remove paginate_by = 20
everything works ok.
That seems pagination occurs before ListFilter and converts queryset to list.
Because I use Django Admin interface
, it's not proper to change ObjectManager and because I use nested serializers
overriding queryset on views does not work either (filters products and nested galleries will not filter).
I'm using Django 1.8.6 with DRF 3.1.3 on Python 3.4
Upvotes: 0
Views: 628
Reputation: 5475
You can solve this by filtering your Products
in get_queryset
and use IsDeletedFilteredListSerializer
to only filter your galleries
.
You can do like:
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)
and in your ProductSerializer
remove the list_serializer_class
option in serializer Meta class.
class ProductSerializer(serializers.ModelSerializer):
galleries = GallerySerializer(many=True, read_only=True)
class Meta:
model = Product
This way you can filter both products
and gallaries
Upvotes: 1