Home > Software design >  filter price range by django-filter
filter price range by django-filter

Time:06-27

I added a price range filter by Django-filter but seems it doesn't work

filters.py

from django_filters import FilterSet
from .models import Apartment

class ApartmentFilter(FilterSet):
    class Meta:
        model = Apartment
        fields = {
            'price': ['lt','gt']
        }

views.py

class ApartmentViewSet(viewsets.ModelViewSet):
    queryset = Apartment.objects.all().order_by('-timestamp')
    serializer_class = ApartmentSerializer
    permission_classes = [
        permissions.IsAuthenticatedOrReadOnly, IsOwnerApartmentOrReadOnly]

    filter_backends = [filters.SearchFilter,
                       DjangoFilterBackend, filters.OrderingFilter]
    filter_class = ApartmentFilter
    search_fields = ['address']
    filterset_fields = ['category', 'district']
    ordering_fields = ('price',)

CodePudding user response:

You can use built-in RangeFilter:

from django_filters import FilterSet, RangeFilter


class ApartmentFilter(FilterSet):
    price = RangeFilter()

    class Meta:
        model = Apartment
        fields = ['price']

Then, in your request parameters send it as price_min and price_max.

E.g. <your_api_endpoint>/?price_min=100&price_max=200

CodePudding user response:

class ApartmentFilter(filters.FilterSet):
    min_price = filters.NumberFilter(field_name="price", lookup_expr='gt')
    max_price = filters.NumberFilter(field_name="price", lookup_expr='lt')
    class Meta:
        model = Apartment
        fields = ['category', 'district']

class ApartmentViewSet(viewsets.ModelViewSet):
    queryset = Apartment.objects.all().order_by('-timestamp')
    serializer_class = ApartmentSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerApartmentOrReadOnly]
    filter_backends = [filters.SearchFilter, DjangoFilterBackend, filters.OrderingFilter]
    filter_class = ApartmentFilter
    search_fields = ['address']

More on documentation here

  • Related