【问题标题】:Serialize ManyToMany field drf haystack序列化多对多字段 drf haystack
【发布时间】:2019-11-12 15:38:31
【问题描述】:

我正在尝试序列化包含与另一个模型的多对多关系的字段。 我使用 drf-haystack 通过 haystack (elasticsearch) 对结果进行序列化。

通常,我会在 modelsearchserializer 中为 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&lt;p&gt;&amp;nbsp;fewfewefwfe&lt;/p&gt;\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'>)"))

我在尝试重建索引时收到此错误消息

【问题讨论】:

  • 能否请您也提供堆栈跟踪?
  • @decibyte 我添加了错误信息

标签: django elasticsearch django-haystack


【解决方案1】:

错误信息是正确的:您正在尝试序列化 M2mfield 实例的复杂值,这是不可能的。在prepare_m2mfield() 中,您应该返回一个简单的、可序列化的值。在您的情况下,可能是dicts 中的list,其中每个dict 代表您希望在搜索索引中出现的来自M2mfield 的字段值。

【讨论】:

  • 能否提供一个代码sn-p
猜你喜欢
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 2015-08-26
相关资源
最近更新 更多