我使用棉花糖-sqlalchemy对数据进行序列化/反序列化。
当我尝试反序列化以下数据时(数据库中存在id = 1的Model2,而id = 2则没有),反序列化器会尝试为id = 2创建新行。如果给定的models2 id在数据库中不存在,如何更改此行为以添加错误?
示例输入:
input = {
"id": 1,
"models2": [{"id": 1}, {"id": 2}]
}
我的模特:
class Model1(db.Model):
__tablename__ = 'model1'
id = db.Column(db.Integer, primary_key=True)
models2 = relationship('Model2', secondary='Model1Model2', backref='models1')
class Model1Model2(db.Model):
__tablename__ = 'model1_model2'
id = db.Column(db.Integer, primary_key=True)
model1_id = db.Column(Integer, ForeignKey('model1.id', ondelete='CASCADE'))
model2_id = db.Column(Integer, ForeignKey('model2.id'))
class Model2(db.Model):
__tablename__ = 'model2'
id = Column(Integer, primary_key=True)
name = Column(String)
我的模式:
class BaseSchema(ModelSchema):
class Meta:
sqla_session = SESSION
class Model2Schema(BaseSchema):
class Meta(BaseSchema.Meta):
model = Model2
dump_only = ('name',)
class Model1Schema(BaseSchema):
class Meta(BaseSchema.Meta):
model = Model1
fields = ('id', 'name')
models2 = Nested(Model2Schema, many=True, only=('id'))