You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Flask-RESTful的@marshal_with序列化DocumentSet的文档ID列表?

解决Flask-RESTful序列化DocumentSet返回document_ids列表的问题

我来帮你搞定这个序列化的问题~你想要把DocumentSet对象序列化成包含id和document_ids(对应所有关联Document的id列表)的结构,之前的写法之所以不生效,是因为Flask-RESTful的字段处理逻辑和你预期的不太一样,下面给你两种可行的正确写法:

方法1:使用attribute配合lambda表达式

这种方式直接通过attribute参数指定如何从DocumentSet对象中提取document_ids的数据:

from flask_restful import fields, marshal_with

# 定义序列化字段结构
document_set_serializer = {
    'id': fields.Integer,
    # 用lambda遍历documents列表,提取每个Document的id
    'document_ids': fields.List(fields.Integer, attribute=lambda doc_set: [doc.id for doc in doc_set.documents])
}

# 在你的Flask-RESTful资源方法上使用装饰器
class DocumentSetResource(Resource):
    @marshal_with(document_set_serializer)
    def get(self, document_set_id):
        # 假设这里获取到了DocumentSet实例
        doc_set = DocumentSet.query.get(document_set_id)
        return doc_set

方法2:使用fields.Function字段

fields.Function允许你自定义一个函数来生成字段的值,灵活性更高:

from flask_restful import fields, marshal_with

document_set_serializer = {
    'id': fields.Integer,
    'document_ids': fields.Function(lambda doc_set: [doc.id for doc in doc_set.documents])
}

# 资源类写法和上面一致

为什么之前的写法失效?

  • 第一种尝试attribute='documents.id':Flask-RESTful的fields.List无法解析这种嵌套的属性路径,documents是一个列表对象,它本身并没有id属性,所以这种写法会导致无法正确提取数据。
  • 第二种尝试fields.List(fields.Nested({'id':fields.Integer}), attribute='documents'):这种写法会生成包含每个Documentid对象的数组,比如[{"id":1}, {"id":2}],而不是你需要的纯id数组[1,2,3]。

这两种正确写法都能帮你得到预期的输出格式:

{ "id": 5, "document_ids": [1, 2, 3] }

内容的提问来源于stack exchange,提问作者W.P. McNeill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:00:58