Все классы SearchIndex должны использовать одно и то же имя поля text для поля document=True. Оскорбительный индекс: '‹personal.search_indexes.PostIndex.

Я пытаюсь создать несколько запросов, используя haystack-whoosh, моя последняя проблема решается путем добавления двойной обратной косой черты, но теперь появилась новая ошибка. Я получаю сообщение об ошибке ниже в командной строке:

   C:\Users\varun\Desktop\Project\mysite>python manage.py rebuild_index
C:\Python34\lib\importlib\_bootstrap.py:321: RemovedInDjango110Warning: django.core.context_processors is deprecated in favor of django.template.context_processors.
  return f(*args, **kwds)

WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'.
Your choices after this are to restore from backups or rebuild via the `rebuild_index` command.
Are you sure you wish to continue? [y/N] y
Removing all documents from your index because you said so.
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python34\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python34\lib\site-packages\django\core\management\base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "C:\Python34\lib\site-packages\haystack\management\commands\rebuild_index.py", line 32, in handle
    call_command('clear_index', **options)
  File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 119, in call_command
    return command.execute(*args, **defaults)
  File "C:\Python34\lib\site-packages\django\core\management\base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "C:\Python34\lib\site-packages\haystack\management\commands\clear_index.py", line 53, in handle
    backend.clear(commit=self.commit)
  File "C:\Python34\lib\site-packages\haystack\backends\whoosh_backend.py", line 232, in clear
    self.setup()
  File "C:\Python34\lib\site-packages\haystack\backends\whoosh_backend.py", line 119, in setup
    self.content_field_name, self.schema = self.build_schema(connections[self.connection_alias].get_unified_index().all_searchfields())
  File "C:\Python34\lib\site-packages\haystack\utils\loading.py", line 342, in all_searchfields
    self.build()
  File "C:\Python34\lib\site-packages\haystack\utils\loading.py", line 237, in build
    self.collect_fields(index)
  File "C:\Python34\lib\site-packages\haystack\utils\loading.py", line 245, in collect_fields
    raise SearchFieldError("All 'SearchIndex' classes must use the same '%s' fieldname for the 'document=True' field. Offending index is '%s'." % (self.document_field, index))
haystack.exceptions.SearchFieldError: All 'SearchIndex' classes must use the same 'text' fieldname for the 'document=True' field. Offending index is '<personal.search_indexes.PostIndex object at 0x00000000056DFCA8>'.

settings.py

HAYSTACK_CONNECTIONS = {
     'autocomplete': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': 'C:\\Users\\varun\\Desktop\\Project\\mysite\\personal\\templates\\search\\indexes,
        'STORAGE': 'file',
        'POST_LIMIT': 128 * 1024 * 1024,
        'INCLUDE_SPELLING': True,
        'BATCH_SIZE': 100,
        'EXCLUDED_INDEXES': ['thirdpartyapp.search_indexes.BarIndex'],
    },
}

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

в то время как мой search_indexes.py читает

    import datetime
from haystack import indexes
from .models import Post
from django.contrib.auth import authenticate, get_user_model

class PostIndex(indexes.SearchIndex,indexes.Indexable):
    text = indexes.CharField(document=True,use_template=True)
    type_of_truck = indexes.CharField(model_attr='type_of_truck')
    date = indexes.DateField(model_attr='date')
    #slug = indexes.SlugField(unique=True)
    weight = indexes.DecimalField(model_attr='weight')
    Material_Name = indexes.CharField(model_attr='Material_Name')
    To = indexes.CharField(model_attr='To')
    Number_Of_Truck = indexes.CharField(model_attr='Number_Of_Truck')
    #Time = indexes.TimeField()
    Volume = indexes.CharField(model_attr='Volume')
    Material_Type = indexes.CharField(model_attr='Material_Type')

    content_auto = indexes.EdgeNgramField(model_attr='from1')

    def get_model(self):
        return Post
    def index_queryset(self,using=None):
            """used when entire index for model is updated."""
            return self.get_model().objects.all()   

модели.py

class Post(models.Model):

    id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    from1 = models.CharField(max_length=20)
    type_of_truck = models.CharField(max_length=20)
    date = models.DateField()
    slug = models.SlugField(unique=True)
    weight = models.DecimalField( max_digits=5, decimal_places=2)
    Material_Name = models.CharField(max_length=20)
    To = models.CharField(max_length=20)
    Number_Of_Truck = models.CharField(max_length=20)
    Time = models.TimeField()
    Volume = models.CharField(max_length=20)
    Material_Type = models.CharField(max_length=20)
    #updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

Post_text

{{object.from1}}
{{object.To}}
{{object.Material_Type}}

в то время как я только что добавил «из haystack.query import SearchQuerySet» в свой views.py, поскольку ранее мой поисковый запрос работал, но я мог искать только один запрос за раз, в то время как я хочу создать запрос с несколькими фильтрами

пожалуйста, помогите, почему я получаю ошибку


person varun maurya    schedule 15.07.2016    source источник


Ответы (1)


В каждом поисковом индексе должно быть поле с document=True с одинаковым именем во всех поисковых индексах, например:

class FirstIndex(ndexes.SearchIndex,indexes.Indexable):
    text = indexes.EdgeNgramField(document=True)

class SecondIndex(ndexes.SearchIndex,indexes.Indexable):
    text = indexes.EdgeNgramField(document=True)

Следующее, что вы не можете использовать model.CharField в качестве поля индекса! Вам нужно использовать:

indexes.<field_type>
person RydelW    schedule 21.07.2016
comment
спасибо @RydelW за ваш ответ ... я внес изменения, и они работают ... и теперь у меня возникла еще одна проблема, для которой я задал другой вопрос, который я не могу искать по нескольким запросам одновременно. - person varun maurya; 24.07.2016
comment
Что вы подразумеваете под несколькими запросами одновременно? Можете ли вы показать код и где именно возникает ошибка? - person RydelW; 26.07.2016