gpt4 book ai didi

django - 在 SearchQuerySet 结果 Haystack 中获取外键对象

转载 作者:行者123 更新时间:2023-11-29 02:49:28 29 4
gpt4 key购买 nike

我有以下模型:

class EquipmentModel(models.Model):
name = models.CharField(max_length=64, blank=False)
description = models.CharField(max_length=64, blank=True)
manufacturer = models.ForeignKey(Manufacturer, related_name="manufacturer")
....

和以下索引:

class EquipmentModelIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr="name")
manufacturer = indexes.CharField()

def get_model(self):
return EquipmentModel

def index_queryset(self, using=None):
return self.get_model().objects.all()

还有我的 equipmentmodel_text.txt

{{ 对象名称 }}{{ object.manufacturer }}

但是,每当我执行此查询时:

    results = SearchQuerySet().models(EquipmentModel).filter(name__startswith=request.GET['q'])[:5]

我只得到制造商的 pk。我想要整个对象(或至少它的名称)。这可能吗?!

谢谢!

最佳答案

要实现这一点,您必须已经 add the manufacturer's name索引时到索引:

class EquipmentModelIndex(indexes.SearchIndex, indexes.Indexable):
# your other fields
manufacturer_name = indexes.CharField()

def index_queryset(self, using=None):
# using select_related here should avoid an extra query for getting
# the manufacturer when indexing
return self.get_model().objects.all().select_related('manufacturer')

def prepare_manufacturer_name(self, obj):
return obj.manufacturer.name

关于django - 在 SearchQuerySet 结果 Haystack 中获取外键对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16848787/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com