簡體   English   中英

序列化多對多字段 drf haystack

[英]Serialize ManyToMany field drf haystack

我正在嘗試序列化一個包含與另一個 model 的多對多關系的字段。 我使用 drf-haystack 通過 haystack (elasticsearch) 序列化結果。

通常,我會在 modelsearchserializer 中為 m2mfield 包含一個 m2mfield 序列化器,但不知何故,當我之后重建索引時,序列化會給出一個錯誤,說它無法序列化。

此 m2mfield 不必是可搜索的。

索引 Model:

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'>)"))

當我嘗試重建索引時收到此錯誤消息

錯誤消息是正確的:您正在嘗試序列化M2mfield實例的復雜值,這是不可能的。 prepare_m2mfield()中,您應該返回一個簡單的、可序列化的值。 在您的情況下,可能是一個dict list ,其中每個dict表示您希望在搜索索引中的M2mfield中的字段值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM