我有一个名为Poll
的模型,该模型与另一个名为Choice
的模型具有一对多关系。1民意测验可以有很多选择。每次保存调查时,我都希望将该调查保存在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。我在做什么错了?
答案 0 :(得分:1)
创建轮询后,将生成信号,并且此时数据库中未填充Choice数据。我遇到了同样的问题,我通过在芹菜中添加延迟的后台任务来为文档建立索引来解决了这个问题。