5.11.drf的搜索和排序

搜索

goods/views.py

from rest_framework import filters

class GoodsCategoryViewSet(ListModelMixin, GenericViewSet):
    """
    获取商品类型列表
    """
    filter_backends = (..., filters.SearchFilter)
    search_fields = ('=name',)

The search behavior may be restricted by prepending various characters to the search_fields.

  • '^' Starts-with search.

  • '=' Exact matches.

  • '@' Full-text search. (Currently only supported Django's PostgreSQL backend.)

  • '$' Regex search.

For example:

search_fields = ['=username', '=email']

排序

class GoodsCategoryViewSet(ListModelMixin, GenericViewSet):
    """
    获取商品类型列表
    """
    ...
    filter_backends = (..., filters.OrderingFilter)
    ordering_fields = ['add_time']

Last updated

Was this helpful?