如何在分配给未映射到SQLAlchemy列的属性时引发异常?

时间:2012-08-20 04:23:30

标签: python sqlalchemy

使用SQLAlchemy,我发现有时候我错误地键入了一个映射到列的属性名称,这导致很难捕获错误:

class Thing(Base):
    foo = Column(String)


thing = Thing()
thing.bar = "Hello" # a typo, I actually meant thing.foo
assert thing.bar == "Hello" # works here, as thing.bar is a transient attribute created by the assignment above
session.add(thing)
session.commit() # thing.bar is not saved in the database, obviously
...
# much later
thing = session.query(Thing)...one()
assert thing.foo == "Hello" # fails
assert thing.bar == "Hello" # fails, there's no even such attribute

是否有办法配置映射类,因此分配给未映射到SQLAlchemy列的任何内容都会引发异常?

2 个答案:

答案 0 :(得分:1)

好的,解决方案似乎是覆盖基类的__setattr__方法,这允许我们在设置之前检查属性是否已存在。

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)

SQLAlchemy的“严格模式”排序......

答案 1 :(得分:0)

覆盖对象的__get__方法,并检查它是否在列中(通过将其与类定义或运行时搜索一起存储)

来自SO的更多信息here