Django haystack, How to search for a ManyToMany related field?
Asked Answered
Y

2

6

I've added a MultivaluedField to my index (haystack), I need to search for a ManyToMany related field, but it doesn't work.

The engine is WHOOSH.

This how my index looks like:

 class PostIndex(SearchIndex):
     text = CharField(document=True, use_template=True)
     author = CharField(model_attr='author') 
     body = CharField(model_attr='body') 
     pub_date = DateTimeField(model_attr='publish') 
     regions = MultiValueField() 
 
 def prepare_regions(self, obj):
     return [region.name for region in obj.regions.all()]

And this how my model looks like:

 class Post(models.Model):

     title           = models.CharField(_('title'), max_length=200)
     author          = models.ForeignKey(User, blank=True, null=True)
     body            = models.TextField(_('body'), )
     allow_comments  = models.BooleanField(_('allow comments'), default=True)
     publish         = models.DateTimeField(_('publish'), default=datetime.datetime.now)
     categories      = models.ManyToManyField(Category, blank=True)
     tags            = TagField()
     objects         = PublicManager()

     regions         = models.ManyToManyField(Region, blank=True)

If I use SearchQuerySet().filter(region__in=words_list) it works. The problem is that I don't know when the user is searching for a region or another field, so I have to use SearchQuerySet().filter(content__icontains=words_list). And in this way nothing is found.

Thanks

Thanks!!

Yesterday answered 27/8, 2010 at 6:55 Comment(3)
did you add regions field to your index template ?Sissified
Try using Solr. Much, much faster.Bodily
What about just adding {{ object.regions.all | join:" " }} in template of text field?Colorful
A
0

Try :

class PostIndex(SearchIndex):
 text = CharField(document=True, use_template=True)
 author = CharField(model_attr='author') 
 body = CharField(model_attr='body') 
 pub_date = DateTimeField(model_attr='publish') 

 regions = CharField(model_attr='regions')
Anderson answered 13/8, 2011 at 0:0 Comment(0)
H
0

You only add region id to the index for Region.

Try

    def prepare_regions(self, obj):
        return [region.pk for region in obj.regions.all()]
Hilleary answered 21/7, 2015 at 16:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.