验证sqlalchemy关系

时间:2016-07-19 17:45:25

标签: python sqlalchemy

我有一个这样的模型:

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,是否有办法让我用一个函数验证这两个字段?

1 个答案:

答案 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