Django elasticsearchdsl在预保存时更新M2M

2024-06-08 21:33:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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)

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

我的问题是,当我更新帖子上的来源时,出于某种原因,elasticsearch索引在保存前更新,而不是在保存后更新。基本上,我必须对相同的来源执行两次put请求,以便在索引中反映更改。我在我的文档中添加了一个def prepare_sources(self, instance):作为我的文档的一部分,它似乎可以工作,但感觉它以后会导致性能问题。任何帮助或指导都将不胜感激


Tags: instancenamepyselffieldsgetmodelsdef
1条回答
网友
1楼 · 发布于 2024-06-08 21:33:13

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

相关问题 更多 >