5

使用 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 列的任何内容会引发异常?

4

2 回答 2

3

好的,解决方案似乎是覆盖__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 的“严格模式”...

于 2012-11-14T05:04:36.067 回答
0

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

SO的更多信息。

于 2012-08-20T04:44:45.487 回答