我需要在我的模型中进行文本搜索并同时使用db查询进行过滤.
例如:
class MyModel(models.Model):
text = models.TextField()
users = models.ManyToMany(User)
class MyModelIndexIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, model_attr='text')
def get_model(self):
return MyModel
Run Code Online (Sandbox Code Playgroud)
所以我希望按用户和所有文本通过全文搜索过滤所有MyModel对象.Smth喜欢这些:
qs = MyModel.objects.filter(users=request.user)
sqs = MyModelIndex.objects.filter(text=request.GET['q'])
intersection = some_magic_function(qs, sqs)
Run Code Online (Sandbox Code Playgroud)
要么
intersection = some_other_magic_function(
qs_kwargs={'users': request.user},
sqs_kwargs={'text': request.GET['q']}
)
Run Code Online (Sandbox Code Playgroud)
当然,期望的数据库查询可能要复杂得多.
我看到一些可能的解决方案,都有重大缺陷:
在django中进行交集:从qs中提取id并在sqs过滤器中使用它们,反之亦然.问题:表现.我们可以通过使用分页来解决它,并且仅对给定页面及其前身进行交集.在这种情况下,我们失去了总数(
索引所有m2m相关字段.问题:性能,重复功能(我相信db会更好地进行此类查询),db-features(如注释等).
不要使用haystack(Go for mysql或posgresql内置全文搜索.
我相信我会错过一些明显的东西 案例似乎很常见.有传统的解决方案吗?
def export_to_excel(request):
lists = MyModel.objects.all()
# your excel html format
template_name = "sample_excel_format.html"
response = render_to_response(template_name, {'lists': lists})
# this is the output file
filename = "model.csv"
response['Content-Disposition'] = 'attachment; filename='+filename
response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-16'
return response
Run Code Online (Sandbox Code Playgroud)
from django.conf.urls.defaults import *
urlpatterns = patterns('app_name.views',
url(r'^export/$', 'export_to_excel', name='export_to_excel'),
)
Run Code Online (Sandbox Code Playgroud)
<a href="{% url app_name:export_to_excel %}">Export</a>
Run Code Online (Sandbox Code Playgroud)
什么都没有获取文件选项下载,没有给出任何错误,但我可以看到所有结果在日志中工作正常.