Files
thrillwiki_django_no_react/search/README.md

106 lines
2.5 KiB
Markdown

# Search & Filter System
A flexible, reusable search and filtering system that can be used across any Django model in the project.
## Features
- Modular filter system with composable mixins
- HTMX integration for dynamic updates
- Responsive, accessible filter UI components
- Automatic filter generation based on model fields
- Location-based filtering support
- Flexible template system
## Usage
### Basic Implementation
Add filtering to any ListView by using the `HTMXFilterableMixin`:
```python
from django.views.generic import ListView
from search.mixins import HTMXFilterableMixin
class MyModelListView(HTMXFilterableMixin, ListView):
model = MyModel
template_name = "myapp/mymodel_list.html"
search_fields = ['name', 'description'] # Fields to include in text search
```
### Custom Filters
Add custom filters for specific model needs:
```python
additional_filters = {
'category': ChoiceFilter(choices=MyModel.CATEGORY_CHOICES),
'rating': RangeFilter(field_name='average_rating'),
}
```
### Template Integration
Extend the base filtered list template:
```html
{% extends "search/layouts/filtered_list.html" %}
{% block list_actions %}
<a href="{% url 'myapp:create' %}" class="btn btn-primary">
Add New
</a>
{% endblock %}
```
### Custom Result Display
Create a custom results template in `templates/search/partials/mymodel_results.html`:
```html
<div class="divide-y">
{% for object in object_list %}
<div class="p-4">
<h3>{{ object.name }}</h3>
<!-- Custom display logic -->
</div>
{% endfor %}
</div>
```
## Components
### Mixins
- `LocationFilterMixin`: Adds location-based filtering
- `RatingFilterMixin`: Adds rating range filters
- `DateRangeFilterMixin`: Adds date range filtering
### Factory Function
Use `create_model_filter` to dynamically create filters:
```python
MyModelFilter = create_model_filter(
model=MyModel,
search_fields=['name', 'description'],
mixins=[LocationFilterMixin, RatingFilterMixin],
additional_filters={...}
)
```
### Template Tags
- `model_name`: Get human-readable model name
- `groupby_filters`: Group filter fields logically
- `add_field_classes`: Add Tailwind classes to form fields
## Performance Considerations
- Use `select_related` and `prefetch_related` in your querysets
- Index commonly filtered fields
- Consider caching for static filter choices
- Use the built-in pagination
## Examples
See `search/examples.py` for detailed implementation examples across different model types.