marshmallow - include_fk失败,如果foreign_key不是int



在使用sql-alchemy和marshmallow序列化相关数据库实体时,我遇到了以下问题:在转储此模式时,调试器会抛出带有消息

ValueError
self._serialize(d, many=False)
value = field_obj.serialize(attr_name, obj, accessor=self.get_attribute)
return self._serialize(value, attr, obj, **kwargs)
ret = self._format_num(value)  # type: _T
return self.num_type(value)
ValueError: invalid literal for int() with base 10: 'sub'

标准库似乎试图将键转换为Integer。出于可读性原因,本例中键是String,因此强制转换显然失败。是否有一个标志来避免转换foreign_key?

以下是可供参考的模型:父类
class Operation(db.Model):
__tablename__ = "operation"
key = db.Column(db.String(64), primary_key=True)
label = db.Column(db.String(128), nullable=False)
rules = db.relationship('app.models.rule.Rule', backref="operation")

子类

class Rule(db.Model):
__tablename__ = 'rule'
id = db.Column(db.Integer, primary_key=True, autoincrement="auto")
operation_key = db.Column(db.Integer, ForeignKey('operation.key'))
class RuleSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Rule
include_fk = True

找到解决方法。添加具有模式唯一条件的嵌套字段。Api。序列化后的json将外键嵌套到对象中。'operation': {'key': 'sub'}

class RuleSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Rule
#    include_fk = True
operation = ma.Nested(OperationSchema, only=('key',))

相关内容

  • 没有找到相关文章

最新更新