我正在尝试序列化一个包含与另一个模型的多对多关系的字段。我使用drf-haystack通过haystack (elasticsearch)来序列化结果。
通常,我会在模型搜索序列化程序中包含m2mfield的m2mfield序列化程序,但不知何故,当我后来重新构建索引时,序列化会给出一个错误,说它无法序列化。
此m2mfield不必是可搜索的。
索引模型:
class ModelIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title', boost=2.5)
model_id = indexes.IntegerField(model_attr='id')
m2mfield = indexes.MultiValueField()
date = indexes.DateField(model_attr='date')
site_id = indexes.IntegerField()
def get_model(self):
return Model
def prepare_m2mfield(self, obj):
return [m2mfield for m2mfield in obj.m2mfield.all()]
def prepare_site_id(self, obj):
return obj.site.id
def index_queryset(self, using=None):
# Used when the entire index for model is updated.
return self.get_model().objects.all().filter(date__lte=datetime.datetime.now()).prefetch_related('m2mfield')序列化程序:
class ModelSearchSerializer(HaystackSerializer):
/* Tried including a serializer for m2mfield here, but didnt work */
class Meta:
index_classes = [ModelIndex]
fields = ['title', 'text', 'date', 'm2mfield', 'model_id']错误消息:
elasticsearch.exceptions.SerializationError: ({'id': 'testdata.model.3', 'django_ct': 'testdata.model', 'django_id': '3', 'text': 'nog 1\n<p>&nbsp;fewfewefwfe</p>\n', 'title': 'nog 1', 'model_id': 3, 'm2mfields': [<M2mfield: homepage>], 'date': '2019-04-24T00:00:00', 'site_id': 31}, TypeError("Unable to serialize <M2mfield: homepage> (type: <class 'main.models.M2mfield'>)"))我在尝试重建索引时收到此错误消息
发布于 2019-11-13 18:37:02
错误消息是正确的:您正在尝试序列化M2mfield实例的复杂值,这是不可能的。在prepare_m2mfield()中,您应该返回一个简单的可序列化的值。在您的示例中,可能是dict的list,其中每个dict表示您希望在搜索索引中包含的来自M2mfield的字段值。
https://stackoverflow.com/questions/58821956
复制相似问题