我想继承通用滤波包括(filterset_fields
,search_fields
,ordering_fields
)在额外动作sold
。那么怎么做呢,对于这个例子有更好的方法吗?
class ApartmentViewset(viewsets.ModelViewSet):
queryset = Apartment.objects.all().order_by('-timestamp')
serializer_class = ApartmentSerializer
# Set permission for only user owner apartment can edit it.
permission_classes = [
permissions.IsAuthenticatedOrReadOnly, IsOwnerApartmentOrReadOnly]
# Add search by address, filter by district and ordering by price
filter_backends = [filters.SearchFilter,
DjangoFilterBackend, filters.OrderingFilter]
filterset_fields = ['district']
search_fields = ['address', 'seller']
ordering_fields = (
'price',
)
# fill current username when create new apartment
def perform_create(self, serializer):
serializer.save(seller=self.request.user)
@action(detail=False)
def sold(self, request):
queryset = self.queryset.filter(issold=True)
serialize = self.serializer_class(queryset, many=True)
return Response(serialize.data)
Generic View(因此所有从它继承的类)在DRF中有一个filter_queryset
方法,它被各种mixins调用来执行过滤,所以你可以简单地在你的方法中调用它。如果你也想要分页,有paginate_queryset
和get_paginated_response
方法:
class ApartmentViewset(viewsets.ModelViewSet):
...
@action(detail=False)
def sold(self, request):
queryset = self.filter_queryset(self.queryset.filter(issold=True))
serialize = self.serializer_class(queryset, many=True)
return Response(serialize.data)