【问题标题】:django throwing error "Cannot convert model field category to an Elasticsearch field!"django 抛出错误“无法将模型字段类别转换为 Elasticsearch 字段!”
【发布时间】:2019-08-24 06:19:01
【问题描述】:

我正在使我的模型与弹性搜索一起工作,我在我的应用目录的documents.py中添加了简单的代码,但是

$ ./manage.py search_index --rebuild

给予

“django_elasticsearch_dsl.exceptions.ModelFieldNotMappedError:无法将模型字段类别转换为 Elasticsearch 字段!”

models.py

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])

文档.py

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',
        ]

【问题讨论】:

  • 这个问题你解决了吗?我也面临同样的问题

标签: django python-3.x elasticsearch-5


【解决方案1】:

https://django-elasticsearch-dsl.readthedocs.io/en/latest/fields.html

问题是外键。 Elasticsearch 不是关系型数据库,所以你必须告诉它某种方式来存储你的 ForeignKey 数据

试试

@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]

这里,ForeignKey 数据存储为文本字段。

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2017-02-23
    • 1970-01-01
    • 2022-01-02
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多