Reputation: 31
I'm making my models work with elastic search and I added simple code in documents.py in my app directory but
$ ./manage.py search_index --rebuild
Gives
"django_elasticsearch_dsl.exceptions.ModelFieldNotMappedError: Cannot convert model field category to an Elasticsearch field!"
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=30)
slug = models.SlugField( default="cslug")
picture = models.FileField(upload_to="static/product_pics/")
parent = models.ForeignKey('self', blank=True,null=True,on_delete=models.CASCADE, related_name='children')
class Meta :
ordering = ('name', )
unique_together = ('slug', 'parent',)
verbose_name_plural = 'Categories'
def get_absolute_url(self):
return reverse('store:productlist', args=[])
def __str__(self):
full_path = [self.name]
k=self.parent
while k is not None:
full_path.append(k.name)
k=k.parent
return '->'.join(full_path[::-1])
from django_elasticsearch_dsl import Document
from django_elasticsearch_dsl.registries import registry
from .models import Category, Brand, Product
@registry.register_document
class CategoryDocument(Document):
class Index:
name = 'categories'
settings = {'number_of_shards': 1,
'number_of_replicas': 0}
class Django:
model = Category
fields = [
'name',
]
Upvotes: 3
Views: 2133
Reputation: 354
https://django-elasticsearch-dsl.readthedocs.io/en/latest/fields.html
The problem is the ForeignKey. Elasticsearch is not a relational database, so you have to tell it some way to store your ForeignKey data
try
@registry.register_document
class CategoryDocument(Document):
parent = fields.ObjectField(properties={
'name': fields.TextField()
})
class Index:
name = 'categories'
settings = {'number_of_shards': 1,
'number_of_replicas': 0}
class Django:
model = Category
fields = [
'name',
]
related_models = [Category]
Here, the ForeignKey data is stored as a text field.
Upvotes: 2