<p>接受的答案是正确的,但效率不高,因为它从数据库中提取行,将结果转换为查询集,最后进行链和排序。。。在</p>
<p>我希望我的回答能帮助别人。我使用的是django oscar和dajngo elasticsearch dsl,我假设您至少使用了elasticsearch dsl。所以你可以简单地</p>
<pre class="lang-py prettyprint-override"><code># *********************************************** documents.py in user module
from django_elasticsearch_dsl import Document
from django_elasticsearch_dsl.registries import registry
from oscar.core.compat import get_user_model
User = get_user_model()
@registry.register_document
class UserDocument(Document):
class Index:
name = 'users'
settings = {
'number_of_shards': 1,
'number_of_replicas': 0
}
class Django:
model = User # < User model class
fields = [
'first_name',
'last_name',
'username'
]
# *********************************************** documents.py in product module
from django_elasticsearch_dsl import Document, TextField
from django_elasticsearch_dsl.registries import registry
from oscar.core.loading import get_model
Product = get_model('catalogue', 'product')
@registry.register_document
class ProductDocument(Document):
upc = TextField(attr='upc', required=False)
class Index:
name = 'products'
settings = {
'number_of_shards': 1,
'number_of_replicas': 0
}
class Django:
model = Product # < Product model class
fields = [
'title',
'description'
]
# *********************************************** search method
from django.shortcuts import render
from elasticsearch_dsl import Search
def global_search(request):
q = request.GET.get('q')
objects = ''
if q:
search = Search(index=['users', 'products'])
objects = search.query("multi_match", query=q, fields=['first_name', 'last_name', 'username', 'title', 'description', 'upc'])
return render(request, 'oscar/search/search.html', {'objects': objects})
</code></pre>