Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get foreign key object in SearchQuerySet results Haystack

I have the following models:

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")
    ....

and the following indexes:

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

and that for my equipmentmodel_text.txt

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

However, whenever I perform this query:

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

I only get the manufacturer's pk. I want the whole object (or at least it's name). Is that possible?!

Thanks!

like image 749
abisson Avatar asked May 31 '13 02:05

abisson


1 Answers

To achieve that you must already add the manufacturer's name to the index when indexing:

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
like image 154
Bernhard Vallant Avatar answered Nov 14 '22 23:11

Bernhard Vallant