python - 如何在 Django 中的模型和相关模型中进行弹性搜索
问题描述
我正在使用在端口号django_elasticsearch_dsl
上运行的,我有两个模型。9200
模型.py
class Category(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
class Book(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
categories = models.ManyToManyField('Category')
文件.py
@posts.doc_type
class PostDocument(DocType):
class Meta:
model = Book
fields = [
'id',
'name'
]
related_models = [Category]
def get_instances_from_related(self, related_instance):
"""If related_models is set, define how to retrieve the book instance(s) from the related model."""
if isinstance(related_instance, Category):
return related_instance.book_set.all()
搜索.py
from elasticsearch_dsl.query import Q
p = Q("multi_match", query=request.GET.get('q'), fields=['name','categories__name'],
type='phrase_prefix')
s = PostDocument.search().query(p)
result = s.execute()
此搜索代码仅适用于书籍模型,我无法使用相关类别模型检索
我需要的输出应该就像我有两本书,比如jungle
和cuop
丛林书链接到 Category
模型(类别名称是sport
)
所以如果搜索?q=ju
输出应该只显示jungle
(使用上面的代码)并且如果搜索 ?q=sport
输出应该只显示jungle
这不起作用(它没有给出任何结果)
解决方案
推荐阅读
- angularjs - 如何使用 downgradeModule 和 angular-cli 在 Angular 混合应用程序中打开 AOT?
- continuous-integration - 在 TFS 2015 中的远程计算机上运行 MSI
- keras - 通用句子编码器错误:输入 0 与层 conv1d_6 不兼容:预期 ndim=3,发现 ndim=2
- java - 文件上传应用程序不能作为 jar 工作
- mysql - 运行基于 MySQL 的 DNS 服务器,2019 年我应该选择哪种技术?
- bash - 尝试使用 crontab 添加以下内容会导致第 2 行出现“糟糕的一分钟”错误
- python - 如何从微秒分配条件循环?
- mysql - 工作台不匹配版本 Mysql 8 到 5.6
- php - 防止 Foreach 数组给出相同的值
- java - 如何在另一个项目中包含一个具有依赖 jar 的 jar 文件作为依赖本身?