Plasma
Plasma

Reputation: 2439

Validating sqlalchemy relationships

I have a model like this:

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")

If I have code like so:

widget = Widget(obj_id=5)

validate_obj_id will fire, but validate_obj will not. Short of looking up obj_id in validate_obj_id and passing the object to validate_obj, is there a way for me to validate both fields with one function?

Upvotes: 4

Views: 1710

Answers (1)

RazerM
RazerM

Reputation: 5482

There is not a way to validate a relationship object that is assigned via its foreign key.


Original Answer

As commented below, this answer is not correct. I can only assume I read the question wrong 5 years ago. This is no better than using @validates and isn't fired when the primary key is assigned to.

You can use the 'set' event:

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

Upvotes: 4

Related Questions