我有一个这样的模型:
class Widget(Base):
obj_id = db.Column(db.Integer, db.ForeignKey("obj.id"))
obj = db.relationship("Obj", back_populates="widgets")
@validates("obj_id")
def validate_obj_id(self, key, obj_id):
return obj_id
@validates("obj")
def validate_obj(self, key, obj):
return obj
class Obj(Base):
widgets = db.relationship("Widget", back_populates="obj")
如果我有这样的代码:
widget = Widget(obj_id=5)
validate_obj_id
会触发,但validate_obj
不会。如果没有在obj_id
中查找validate_obj_id
并将对象传递给validate_obj
,是否有办法让我用一个函数验证这两个字段?
答案 0 :(得分:4)
您可以使用'set'事件:
from sqlalchemy import event
@event.listens_for(Widget.obj, 'set', retval=True)
def validate_obj(target, value, oldvalue, initiator):
print('event fired for validate_obj')
return value