2
votes

Sorry for the noobish question (I'm new with Django) but I was wondering how can I retrieve data from only one field using Django, Haystack with Solr. Example:

I have two models:

class Category(models.Model):
  name = models.CharField("Category name", max_length=255)

class Post(models.Model):
  title = models.CharField("Post title", max_length=255)
  category = models.ManyToManyField(Category, related_name="category")

I indexed the Post model like this:

class PostIndex(SearchIndex):
    text = CharField(document=True, use_template=True)
    title = EdgeNgramField(model_attr='title')
    category = FacetMultiValueField()

    def get_model(self):
        return Post

    def prepare_category(self, obj):
        return obj.category.all()

    def index_queryset(self):
        return self.get_model().objects.all()

site.register(Post, PostIndex)

Here comes the question: How can I retrieve only the Category field using Haystack. I want the categories to appear as facets with counts but without using:

url(r'^search/$', FacetedSearchView(form_class=FacetedSearchForm, searchqueryset=sqs), name='haystack_search'),

in my url.py. I'm using my own view to do the search. Thanks in advance for your answer!



I'm using:

  • Django 1.4
  • Haystack 1.2.7
  • Solr 3.6.1
2

2 Answers

1
votes

You can try the following:

from haystack.query import SearchQuerySet

categories = Category.objects.all()
sqs = SearchQuerySet()

facets = {}
for category in categories:
    facets.update(sqs.facet(category.name).facet_counts()['fields'])

You can iterate through facets in your template to display the values in it along with the counts.

0
votes

Ok this is how i fixed this - I used Thierry Lams code but modified it a bit:

from haystack.query import SearchQuerySet
from myapp.models import Category

categories = Category.objects.all()
sqs = SearchQuerySet()

facets = {}
for category in categories:
    facets.update(sqs.facet('category').facet_counts())

Next, to read the facet variable which is dictionary i did this in the template (the new variable category is actually the facets dictionary): http://tny.cz/40a7bf82