问题
I'm trying to get a MultiValueField to be indexed, but it's just not working. Here is what I have:
class Public_PollIndex(SearchIndex):
text = CharField(model_attr='question', document=True, use_template=True)
date_created = DateTimeField(model_attr='date_created')
choices = MultiValueField()
def get_model(self):
return Public_Poll
def prepare_choices(self, obj):
# For some silly reason we get (u"choice",) instead of just u"choice"
# So we unpack...
c = [ str(c) for (c,) in obj.choice_set.values_list('choice') ]
return c
def index_queryset(self):
return self.get_model().objects.filter(date_created__lte=datetime.datetime.now())
Then I have in the template:
{{ object.question }}
{{ object.date_created }}
{{ object.choices }}
Stepping through with the debugger prepare_choices DOES return something like ['foo', 'bar']
But when I look into solr or Public_PollIndex(Public_Poll.objects.get(id=1)).load_all_queryset() I don't see the choices field indexed, but the other two are.
回答1:
How do you check the SearchQuerySet? Public_PollIndex(Public_Poll.objects.get(id=1)).load_all_queryset() returns model QuerySet instead of SearchQuerySet
Try
SearchQuerySet()[0].text
SearchQuerySet()[0].choices
Also, in the template, render choices in forloop
{% for choice in object.choices %}
{{ choice }}
{% endfor %}
Furthermore,
return obj.choice_set.values_list('choice', flat=True)
# instead of
c = [ str(c) for (c,) in obj.choice_set.values_list('choice') ]
return c
来源:https://stackoverflow.com/questions/10667522/haystack-isnt-indexing-my-multivalue