我正在使用 django-elasticsearch-dsl 包,但有点进退两难。这是我的代码:
模型.py
class Source(models.model):
name = models.CharField(max_length=50)
class Posting(models.Model):
title = models.CharField(max_length=250)
sources = models.ManyToMany(Sources, related_name="postings", through="PostingSource")
class PostingSource(models.Model):
posting = models.ForeignKey(Posting, related_name="posting_sources", on_delete=models.CASCADE)
source = models.ForeignKey(Source, related_name="posting_sources", on_delete=models.CASCADE)
文件.py
class PostingDocument(Document):
sources = fields.ObjectField(properties={"name": fields.KeywordField()})
class Index:
name = "posting"
settings = {"all the settings stuff"}
class Django:
model = Posting
fields = ["title"]
related_models = [PostingSource]
def get_queryset(self):
return super().get_queryset().select_related("sources")
def get_instance_from_related(self, related_instance):
if isinstance(related_instance, PostingSource):
return related_instance.posting
我的问题是,当我更新帖子的来源时,出于某种原因,elasticsearch 索引会更新为 pre_save 而不是 post_save。我基本上必须使用相同的源执行 2 次放置请求,以便更改反映在我的索引中。我def prepare_sources(self, instance):
在文档中添加了一个,它似乎可以工作,但感觉以后会导致性能问题。任何帮助或指导将不胜感激。
经过几个月的测试,我通过添加一个def prepare_sources(self, instance):
我对多对多关系进行非规范化的位置来解决我的第一个问题。我还通过简单地使用.select_related("sources")
有助于提高性能的方式解决了我的第二个问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句