gpt4 book ai didi

Django 抛出错误 "Cannot convert model field category to an Elasticsearch field!"

转载 作者:行者123 更新时间:2023-12-05 05:09:20 25 4
gpt4 key购买 nike

我正在让我的模型与 Elasticsearch 一起工作,我在我的应用程序目录中的 documents.py 中添加了简单的代码,但是

$ ./manage.py search_index --rebuild

给予

"django_elasticsearch_dsl.exceptions.ModelFieldNotMappedError: Cannot convert model field category to an Elasticsearch field!"

模型.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',
]

最佳答案

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]

在这里,外键数据存储为文本字段。

关于Django 抛出错误 "Cannot convert model field category to an Elasticsearch field!",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57635588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com