> For the complete documentation index, see [llms.txt](https://moluo.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://moluo.gitbook.io/notes/bian-cheng-xue-xi/python/django-rest-framework/5.11.drf-de-sou-suo-he-pai-xu.md).

# 5.11.drf的搜索和排序

## 搜索

goods/views.py

```python
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](https://docs.djangoproject.com/en/dev/ref/contrib/postgres/search/).)
* '$' Regex search.

For example:

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

## 排序

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