@validates hangs a marker of the method that mapper() uses when it instruments 
the class, so if the class is already mapped then that train has left the 
station.   Taking a cab instead, you can just add the attribute event directly:

@event.listens_for(Positive.value, "set")
def checkvalue(target, value, oldvalue, initiator)
   assert value > 0

if you want to return a new, mutated value then add retval=True to 
listens_for().


On Apr 15, 2012, at 8:22 AM, lars van gemerden wrote:

> Hi,
> 
> I need a way to dynamically add a validates method to a already
> created sqla class.
> 
> In a normal class declaration you can add a validator by:
> 
> class Positive(Base):
>    __tablename__ = "positives"
>    value = Column(Integer)
> 
>    def checkvalue(self, name, value):
>        assert value > 0
>        return value
>    validates("value")(checkvalue)
> 
> However if you get the class dynamically:
> 
> Positive = type("Positive", (Base,), dict(__tablename__ =
> "positives",  value = Column(Integer)))
> 
> I can't figure out how to add the validator, either in the type() call
> or afterwards.
> 
> Cheers, Lars
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "sqlalchemy" group.
> To post to this group, send email to sqlalchemy@googlegroups.com.
> To unsubscribe from this group, send email to 
> sqlalchemy+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/sqlalchemy?hl=en.
> 

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to