开发者

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

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 lik开发者_Python百科e:

 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!!


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜