首页 > 解决方案 > Elasticsearch dsl 添加外键

问题描述

我有一个名为 的模型,该模型与另一个名为1 pollPoll的模型有一对多的关系,可以有很多选择。Choice每次保存投票时,我都想在 Elasticsearch 中保存该投票。

型号

class Poll(models.Model):
    user            = models.ForeignKey(User, on_delete=models.CASCADE)
    question        = models.CharField(max_length=200)

    def indexing(self):
        obj = QuestionIndex(
            meta={'id': self.id},
            question=self.question,
            choices=self.choice_set.count(), # How many choices are there?
        )
        obj.save()
        return obj.to_dict(include_meta=True)

指数

class QuestionIndex(Document):
    question        = Text()
    choices         = Integer()

    class Index:
        name = 'questions'

我已经在 Django 中添加了一个信号来执行以将数据保存在 Elasticsearch 中。这很好用,但是,即使我添加了选择,我也看到选择的值始终为 0。选择确实保存在我的数据库中,但选择的计数始终为 0。我做错了什么?

标签: djangoelasticsearchdjango-models

解决方案


创建民意调查时会生成信号,此时选择数据不会填充到数据库中。我遇到了同样的问题,我通过在 celery 中添加延迟后台任务来索引文档来解决它。


推荐阅读