python - Django elasticsearch-dsl在pre_save上更新M2M

标签 python django elasticsearch elasticsearch-dsl

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

我的问题是,由于某些原因,当我更新发布中的源时,elasticsearch索引将更新为pre_save而不是post_save。我基本上必须对相同的源执行两次放置请求,以使更改反射(reflect)在索引中。我在文档中添加了def prepare_sources(self, instance):,它似乎可以正常工作,但感觉稍后会导致性能问题。任何帮助或指导将不胜感激。

最佳答案

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

关于python - Django elasticsearch-dsl在pre_save上更新M2M,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60858363/

相关文章:

c# - 在NEST2上删除了INestSerializer

python - 如何创建具有非数字 X 轴的条形图?

javascript - 在您自己的网站上共享带有缩略图的链接

Django 休息框架 : Disable field update after object is created

elasticsearch - 可以列出丢失数据的唯一ID的Elasticsearch查询

elasticsearch - Grafana在Elasticsearch数据源中使用两个字段的减法

python - Speechmatics 提交一份没有音频参数的作业

python - Unicode解码错误: 'ascii' codec can't decode byte 0xa3

python - 无法导入 'keystoneauth1' ...尽管已安装?

python - Django admin - 覆盖已经注册的模型