5

我有以下型号:

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()

以及我的设备模型文本.txt

{{ object.name }} {{ object.manufacturer }}

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

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

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

谢谢!

4

1 回答 1

7

要实现这一点,您必须在索引时将制造商的名称添加到索引中:

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
于 2013-05-31T10:16:22.973 回答