How do I raise an exception when assigning to an attribute which is NOT mapped to an SQLAlchemy column?

后端 未结 2 1077
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 07:00

With SQLAlchemy, I\'m finding that sometimes I mis-type a name of an attribute which is mapped to a column, which results in rather difficult to catch errors:



        
相关标签:
2条回答
  • 2020-12-11 07:09

    Override the __get__ method of objects, and check to see if it is in the column (by storing it with the class definition or runtime search)

    More information here from SO.

    0 讨论(0)
  • 2020-12-11 07:29

    Ok, the solution seems to be to override __setattr__ method of the base class, which allows us to check if the atribute already exists before setting it.

    class BaseBase(object):
        """
        This class is a superclass of SA-generated Base class,
        which in turn is the superclass of all db-aware classes
        so we can define common functions here
        """
    
        def __setattr__(self, name, value):
            """
            Raise an exception if attempting to assign to an atribute which does not exist in the model.
            We're not checking if the attribute is an SQLAlchemy-mapped column because we also want it to work with properties etc.
            See http://stackoverflow.com/questions/12032260/ for more details.
            """ 
            if name != "_sa_instance_state" and not hasattr(self, name):
                raise AttributeError("Attribute %s is not a mapped column of object %s" % (name, self))
            super(BaseBase, self).__setattr__(name, value)
    
    Base = declarative_base(cls=BaseBase)
    

    Sort of "strict mode" for SQLAlchemy...

    0 讨论(0)
提交回复
热议问题