0

在使用 sql-alchemy 和 marshmallow 序列化相关数据库实体时,我遇到了以下问题: On dumping this schema the debugger raises a ValueErrorwith the message

    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'

似乎图书馆试图将密钥转换为整数。出于可读性原因,在这种情况下,键是字符串,因此强制转换显然失败了。是否有一个标志可以避免强制转换外键?

这里的模型供参考:父类

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
4

1 回答 1

0

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

class RuleSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Rule
    #    include_fk = True
    operation = ma.Nested(OperationSchema, only=('key',))
于 2021-08-19T13:08:33.940 回答