Django: Haystack and Elasticsearch with Mongoengin

2019-06-09 05:36发布

I am trying to integrate Haystack Elasticsearch with my django REST application that uses MongoDB as database. Here is my source code:

models.py

class Books(Document):
    ISBN = fields.StringField(null=False, required=True)
    book_name = fields.StringField(null=False, required=True)
    genre = fields.StringField(null=False, required=True)
    author = fields.StringField(null=False, required=True)
    publisher = fields.StringField(null=False,required=True)
    price = fields.IntField(required=True)
    stock = fields.IntField(required=True)

search_indexes.py

class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
book = indexes.CharField(model_attr="book_name")
price = indexes.CharField(model_attr="price")

def get_model(self):
    return Books

def index_queryset(self, using=None):
    return self.get_model().objects.filter(
        created__lte=timezone.now()
    )

serializer.py

class BookIndexSerilizer(HaystackSerializer):
class Meta:
    index_classes = [BookIndex]
    fields = [
        'text', 'book', 'price'
    ]

views.py

class BookSearchView(HaystackViewSet):
index_models = [Books]
serializer_class = BookIndexSerilizer

urls.py

router = routers.DefaultRouter()
router.register('search/', BookSearchView, 'Books')

settings.py

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': 'http://localhost:9200/',
        'INDEX_NAME': 'haystack',
    },
}

When i hit the search URL i get following exception: AttributeError('The model being added to the query must derive from Model.'). What is going wrong?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-09 06:11

the problem is that Books is deriving from Document, it is requiring the model class Books(Document): derives from Model like class Books(models.Model):.

查看更多
登录 后发表回答