[django-haystack] SearchQuerySet with an id in a MultiValue field or an empty MultiValue field

978 views
Skip to first unread message

pablo

unread,
Apr 24, 2010, 2:35:39 PM4/24/10
to django-haystack
Hi,

I have an index with a MultiValueField that holds a m2m field ids.
Given a category id how can I have a SearchQuerySet that consist of
- all the models that matches the category id
- all the models that have empty categories

class MyIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
categories = indexes.MultiValueField()

def prepare_categories(self, obj):
return [category.id for category in obj.categories.all()]

p.s. do I need to add indexed=False and stored=True to the categories
field?

Thanks

--
You received this message because you are subscribed to the Google Groups "django-haystack" group.
To post to this group, send email to django-...@googlegroups.com.
To unsubscribe from this group, send email to django-haysta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-haystack?hl=en.

Daniel Lindsley

unread,
Apr 26, 2010, 2:30:36 AM4/26/10
to django-...@googlegroups.com
pablo,


Finding all models that match the category id is relatively simple
(``sqs = SearchQuerySet().filter(categories=2)`` for instance).
Finding those with no categories is very difficult without adding
another field that tracks the category count. And ``indexed=True,
stored=True`` is the default for all fields, so you do not have to
specify that.


Daniel

pablo platt

unread,
Apr 26, 2010, 4:03:01 AM4/26/10
to django-...@googlegroups.com
As you suggested I'm using categories_empty which is a BooleanField that is True if there are no categories
and I'm using Q to query.

The SearchIndex:
class ProductIndex(indexes.SearchIndex):

    text = indexes.CharField(document=True, use_template=True)
    categories = indexes.MultiValueField()
    empty_categories = indexes.BooleanField()

    def prepare_cars(self, obj):

        return [category.id for category in obj.categories.all()]

    def prepare_empty_cars(self, obj):
        if not obj.categories.count():
            return True
        else:
            return False
site.register(Product, ProductIndex)

The query:
searchqueryset = SearchQuerySet().filter(Q(categories=c.pk) | Q (categories_empty=True))
Reply all
Reply to author
Forward
0 new messages