【问题标题】:Django elasticsearch-dsl updating M2M on pre_saveDjango elasticsearch-dsl 在 pre_save 上更新 M2M
【发布时间】:2020-03-25 22:34:13
【问题描述】:

我正在使用 django-elasticsearch-dsl 包,但有点进退两难。这是我的代码:

models.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)

documents.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

我的问题是,当我更新帖子中的来源时,由于某种原因,弹性搜索索引会更新 pre_save 而不是 post_save。为了使更改反映在我的索引中,我基本上必须使用相同的来源执行 2 次 put 请求。我在文档中添加了def prepare_sources(self, instance):,它似乎可以工作,但感觉以后会导致性能问题。任何帮助或指导将不胜感激。

【问题讨论】:

    标签: python django elasticsearch elasticsearch-dsl


    【解决方案1】:

    经过几个月的测试,我通过添加def prepare_sources(self, instance): 解决了我的第一个问题,我在其中非规范化了我的多对多关系。我还通过简单地使用有助于提高性能的.select_related("sources") 解决了我的第二个问题。

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 2016-06-23
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多