SoFunction
Updated on 2024-11-19

django rest framework using django-filter usage

Notes on django rest framework using django-filter:

Be sure to load the following code inside the setting file instead of just installing the package, otherwise the django app won't report errors but won't filter correctly.

“`
INSTALLED_APPS = [
‘django_filters'
]

REST_FRAMEWORK = {
‘DEFAULT_FILTER_BACKENDS': ( ‘django_filters.rest_framework.DjangoFilterBackend',
),
}

Additional knowledge:Mixing rest_framework-filters and django-filters - Filtering Search

view

from rest_framework.pagination import PageNumberPagination
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework import filters

from django_filters.rest_framework import DjangoFilterBackend

from .models import Goods
from .serializers import GoodsSerializer
# Import filter classes
from .filters import GoodsFilter

class GoodsPagination(PageNumberPagination):
  page_size = 10
  page_size_query_param = "page_size"
  page_query_param = "p"
  max_page_size = 100

class GoodsListViewSet(, ):
  # Specify queryset
  queryset = ()

  # Specify the serialization class
  serializer_class = GoodsSerializer

  # Specify the paging class
  pagination_class = GoodsPagination

  # Add filters Here you can add the django-filter filter to be used in conjunction with the rest_framework filters, or you can use them individually, depending on your needs.
  filter_backends = [DjangoFilterBackend, ]

  # If only simple equivalency-based filtering is needed, then filter_fields can set an attribute on the view or viewset that lists the set of fields to be filtered.
  # Equivalent means that the data in the field you're filtering on must be the same as the data in that field in the database.
  # filter_fields = ['name', 'shop_price']

  # Specify the filter class
  filter_class = GoodsFilter

  search_fields = ['name', 'goods_brief', "goods_desc"]

Filter class - define it according to your needs

import django_filters

from .models import Goods

class GoodsFilter(django_filters.rest_framework.FilterSet):
  """
  Filter Classes for Commodities
  """

  # greater than this value name specified field lookup_expr filter criteria
  # NumberFilter Number Type
  price_min = django_filters.NumberFilter(name="shop_price", lookup_expr="gte")
  # Less than that
  price_max = django_filters.NumberFilter(name="shop_price", lookup_expr="lte")

  # name fuzzy query, do not specify filter, must match all
  # CharFilter string types
  name = django_filters.CharFilter(name="name", lookup_expr="icontains")

  class Meta:
    # Specify the model class
    model = Goods
    # Display these two fields
    fields = ["price_min", "price_max", "name"]

settings

INSTALLED_APPS = [
  # drf filters are also xadmin filters.
  'django_filters',
  'rest_framework',
]

url

from  import url, include

from rest_framework.routers import DefaultRouter

from  import GoodsListViewSet
# Generate a registrar instance object
router = DefaultRouter()
# Register interfaces that require automatic url generation
# Configure the url of the goods
(r'goods', GoodsListViewSet, base_name="goods-list")

urlpatterns = [
  # Auto-generated url
  url(r"^", include()),
]

rendering (visual representation of how things will turn out)

The above django rest framework using django-filter usage is all I have shared with you.