Django的定期事件工具
django-simple-search的Python项目详细描述
django简单搜索提供了相同的功能和便利 在django管理中,search_fields所做的。
有关详细信息,请参见http://gregbrown.co.nz/code/django-simple-search/。
安装
从下载源 https://pypi.python.org/pypi/django-simple-search/然后运行 python setup.py install,或:
> pip install django-simple-search
要求Django 1.8或更高。
快速启动
from simple_search import search_filter from .models import MyModel query = 'test' search_fields = ['^title', 'description', '=id'] f = search_filter(search_fields, query) filtered = MyModel.objects.filter(f)
为了方便起见,您可以通过提供的 工厂:
from .models import MyModel from simple_search import search_form_factory SearchForm = search_form_factory(MyModel.objects.all(), ['^title', 'description'])
参考
simple_search.search_filter(search_fields, query)
给定要搜索的search_fields列表和查询,返回 models.Q对象,可用于筛选查询集。
search_fields的行为与django管理员完全相同 search_fields 选择。示例:
search_fields = [ # match from the start of the title field '^title', # match anywhere within the description field 'description', # match from the start of the related category's title field '^category__title', # exact match on object id '=id' ]
simple_search.search_form_factory(queryset, search_fields)
创建一个搜索表单类,它将根据 search_fields和表单域q。示例:
# forms.py from .models import MyModel from simple_search import search_form_factory SearchForm = search_form_factory(MyModel.objects.all(), ['^title', 'description']) # views.py from django.shortcuts import render from .forms import SearchForm @render('search.html') def search(request): form = SearchForm(request.GET or {}) if form.is_valid(): results = form.get_queryset() else: results = MyModel.objects.none() return { 'form': form, 'results': results, }
运行测试
使用tox(https://pypi.python.org/pypi/tox):
> pip install tox > cd path-to/django-simple-search > tox