我有两个表,PackMatData 和 ColorData:
class PackMatData(db.Model):
id = db.Column(db.Integer, primary_key=True)
unique_name = db.Column(db.String(20), index=True, unique=True)
se_name = db.Column(db.String(20), index=True)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
labflex_name = db.Column(db.String(20))
country = db.Column(db.String(20), index=True)
color_measurements = db.relationship('ColorData', backref='entry', cascade="all, delete-orphan", lazy='dynamic')
class ColorData(db.Model):
id = db.Column(db.Integer, primary_key=True)
color = db.Column(db.String(20), index=True)
patch = db.Column(db.String(10), index=True)
L = db.Column(db.String(10), index=True)
a = db.Column(db.String(10), index=True)
b = db.Column(db.String(10), index=True)
pack_mat_data_id = db.Column(db.Integer, db.ForeignKey('pack_mat_data.id'))
我想加入这些表,然后序列化返回的值。我正在使用 flask-sqlalchemy 左外连接对 PackMatData 表的 id 执行连接:
@app.route('/api/entries')
def entries():
pmcd = db.session.query(PackMatData, ColorData).outerjoin(ColorData, PackMatData.id == ColorData.pack_mat_data_id).all()
data = [{"packmatdata": x[0], "colordata": x[1]} for x in pmcd]
output = NestedSchema(many=True).dump(data)
return jsonify(output)
从联接中,我以元组列表的形式获得了我期望的数据:
[...,(<PackMatData 138>, <ColorData 7272>), (<PackMatData 138>, <ColorData 7285>),(<PackMatData 138>, <ColorData 7286>), (<PackMatData 138>, <ColorData 7287>), (<PackMatData 138>, <ColorData 7284>), (<PackMatData 138>, <ColorData 7283>), (<PackMatData 139>, <ColorData 7321>), (<PackMatData 139>, <ColorData 7322>), (<PackMatData 139>, <ColorData 7323>), (<PackMatData 139>, <ColorData 7320>), (<PackMatData 139>, <ColorData 7319>), (<PackMatData 139>, <ColorData 7311>), ...]
我在 stackoverflow flask-marshmallow 中读到了一个模式中的两个 db 对象,marshmallow 需要一个字典列表,这就是为什么我在将其传递给转储之前进行转换的原因。
以下是我为序列化定义的模式:
class ColorDataSchema(ma.ModelSchema):
class Meta:
model = ColorData
class PackMatDataSchema(ma.ModelSchema):
class Meta:
model = PackMatData
class NestedSchema(ma.ModelSchema):
colordata = ma.Nested(ColorDataSchema)
packmatdata = ma.Nested(PackMatDataSchema, many=True)
问题是转储函数总是返回以下内容:
[...,{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {},...]
我也尝试了这个模式(结果相同):
class PackMatDataSchema(ma.ModelSchema):
class Meta:
model = PackMatData
class ColorDataSchema(ma.ModelSchema):
packmatdata = ma.Nested(PackMatDataSchema, many=True)
class Meta:
model = ColorData
你能引导我走向正确的方向吗?抱歉,这篇文章很长,但我想尽可能多地为您提供详细信息。