|
4 | 4 |
|
5 | 5 | ## **Properties** |
6 | 6 |
|
7 | | -`def paginate(func_or_pgn_class: Any = NOT_SET, **paginator_params: Any) -> Callable[..., Any]:` |
| 7 | +`def paginate(func_or_pgn_class: Any = NOT_SET, filter_schema: Optional[Type[FilterSchema]] = None, **paginator_params: Any) -> Callable[..., Any]:` |
8 | 8 |
|
9 | 9 | - func_or_pgn_class: Defines a route function or a Pagination Class. default: `ninja_extra.pagination.LimitOffsetPagination` |
| 10 | +- filter_schema: Optional FilterSchema class from Django Ninja for filtering querysets before pagination |
10 | 11 | - paginator_params: extra parameters for initialising Pagination Class |
11 | 12 |
|
12 | 13 | ### **Using Ninja LimitOffsetPagination** |
@@ -75,3 +76,127 @@ api.register_controllers(UserController) |
75 | 76 | ``` |
76 | 77 |
|
77 | 78 |  |
| 79 | + |
| 80 | +## **Pagination with Filtering** |
| 81 | + |
| 82 | +You can combine pagination with Django Ninja's `FilterSchema` to provide both filtering and pagination capabilities. Filters are applied to the queryset **before** pagination. |
| 83 | + |
| 84 | +!!! info "Learn More About FilterSchema" |
| 85 | + For comprehensive information about FilterSchema features, custom expressions, combining filters, and advanced filtering techniques, see the official Django Ninja documentation: [https://django-ninja.dev/guides/input/filtering/](https://django-ninja.dev/guides/input/filtering/) |
| 86 | + |
| 87 | +### **Basic Filtering Example** |
| 88 | + |
| 89 | +```python |
| 90 | +from typing import Optional |
| 91 | +from ninja import FilterSchema |
| 92 | +from ninja_extra.pagination import paginate, PageNumberPaginationExtra, PaginatedResponseSchema |
| 93 | +from ninja_extra import api_controller, route, NinjaExtraAPI |
| 94 | +from ninja import ModelSchema |
| 95 | +from myapp.models import Book |
| 96 | + |
| 97 | + |
| 98 | +class BookSchema(ModelSchema): |
| 99 | + class Config: |
| 100 | + model = Book |
| 101 | + model_fields = ['id', 'title', 'author', 'price', 'published_date'] |
| 102 | + |
| 103 | + |
| 104 | +# Define a FilterSchema for your model |
| 105 | +class BookFilterSchema(FilterSchema): |
| 106 | + title: Optional[str] = None |
| 107 | + author: Optional[str] = None |
| 108 | + min_price: Optional[float] = None |
| 109 | + |
| 110 | + |
| 111 | +@api_controller('/books') |
| 112 | +class BookController: |
| 113 | + @route.get('', response=PaginatedResponseSchema[BookSchema]) |
| 114 | + @paginate(PageNumberPaginationExtra, filter_schema=BookFilterSchema, page_size=20) |
| 115 | + def list_books(self): |
| 116 | + return Book.objects.all() |
| 117 | + |
| 118 | + |
| 119 | +api = NinjaExtraAPI(title='Books API') |
| 120 | +api.register_controllers(BookController) |
| 121 | +``` |
| 122 | + |
| 123 | +**Example API calls:** |
| 124 | +- `GET /api/books/?page=1&page_size=20` - Paginated results |
| 125 | +- `GET /api/books/?title=Python&page=1` - Filter by title and paginate |
| 126 | +- `GET /api/books/?author=John&min_price=10&page=2` - Multiple filters with pagination |
| 127 | + |
| 128 | +### **Advanced Filtering with Custom Lookups** |
| 129 | + |
| 130 | +Use Django Ninja's `FilterLookup` annotation for more complex filtering: |
| 131 | + |
| 132 | +```python |
| 133 | +from typing import Annotated, Optional |
| 134 | +from ninja import FilterSchema, FilterLookup |
| 135 | + |
| 136 | + |
| 137 | +class AdvancedBookFilterSchema(FilterSchema): |
| 138 | + # Case-insensitive containment search |
| 139 | + title: Annotated[Optional[str], FilterLookup("title__icontains")] = None |
| 140 | + |
| 141 | + # Exact match on author name |
| 142 | + author: Annotated[Optional[str], FilterLookup("author__name__iexact")] = None |
| 143 | + |
| 144 | + # Greater than or equal to price |
| 145 | + min_price: Annotated[Optional[float], FilterLookup("price__gte")] = None |
| 146 | + |
| 147 | + # Less than or equal to price |
| 148 | + max_price: Annotated[Optional[float], FilterLookup("price__lte")] = None |
| 149 | + |
| 150 | + # Date range filtering |
| 151 | + published_after: Annotated[Optional[str], FilterLookup("published_date__gte")] = None |
| 152 | + |
| 153 | + |
| 154 | +@api_controller('/books') |
| 155 | +class BookController: |
| 156 | + @route.get('', response=PaginatedResponseSchema[BookSchema]) |
| 157 | + @paginate(PageNumberPaginationExtra, filter_schema=AdvancedBookFilterSchema, page_size=20) |
| 158 | + def list_books(self): |
| 159 | + return Book.objects.all() |
| 160 | +``` |
| 161 | + |
| 162 | +### **Using FilterSchema with Model Controllers** |
| 163 | + |
| 164 | +FilterSchema can also be integrated with Model Controllers through the `ModelPagination` configuration: |
| 165 | + |
| 166 | +```python |
| 167 | +from ninja import FilterSchema |
| 168 | +from ninja_extra.controllers import ModelControllerBase |
| 169 | +from ninja_extra.controllers.model import ModelConfig, ModelPagination |
| 170 | +from ninja_extra.pagination import PageNumberPaginationExtra |
| 171 | +from myapp.models import Book |
| 172 | + |
| 173 | + |
| 174 | +class BookFilterSchema(FilterSchema): |
| 175 | + title: Optional[str] = None |
| 176 | + author__name: Optional[str] = None |
| 177 | + price__gte: Optional[float] = None |
| 178 | + |
| 179 | + |
| 180 | +class BookModelController(ModelControllerBase): |
| 181 | + model_config = ModelConfig( |
| 182 | + model=Book, |
| 183 | + pagination=ModelPagination( |
| 184 | + klass=PageNumberPaginationExtra, |
| 185 | + filter_schema=BookFilterSchema, |
| 186 | + paginator_kwargs={"page_size": 25} |
| 187 | + ) |
| 188 | + ) |
| 189 | +``` |
| 190 | + |
| 191 | +This configuration automatically applies the FilterSchema to the `list` endpoint of your Model Controller. |
| 192 | + |
| 193 | +### **How It Works** |
| 194 | + |
| 195 | +1. **Query Parameters**: When a request is made, both filter and pagination parameters are extracted from query parameters |
| 196 | +2. **Filtering**: The FilterSchema validates and applies filters to the queryset first |
| 197 | +3. **Pagination**: The filtered results are then paginated according to the pagination parameters |
| 198 | +4. **Response**: The paginated response includes filtered results with pagination metadata |
| 199 | + |
| 200 | +### **OpenAPI Schema** |
| 201 | + |
| 202 | +When using FilterSchema with pagination, the OpenAPI documentation automatically includes both filter parameters and pagination parameters, making your API self-documenting and easy to use. |
0 commit comments