python - 在 SQLAlchemy 中查询混合属性

标签 python properties sqlalchemy

我将文件路径存储为数据库中的相对路径,但我随后使用混合属性在映射时将其转换为绝对路径。当我使用此属性进行查询时,它会引发错误。这是模型:

class File(Base):
    __tablename__ = 'files'
    ...

    _f_path = Column(Unicode(30))

    ...

    @hybrid_property
    def f_path(self):
        env = shelve.open('environment')
        return os.path.join(env['project_dir'], self._f_path)

    @f_path.setter
    def f_path(self, _f_path):
        self._f_path = _f_path

当我运行此查询时(其中 ref 是一个 unicode 字符串):

session.query(File).filter_by(f_path=ref).first()

它给我这个错误:

File "/Users/Ben/Dropbox/Giraffe/giraffe_server/giraffe/file_handlers/maya.py", line 135, in process_file
    rf = session.query(File).filter_by(f_path=str(ref)).first()
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/query.py", line 1211, in filter_by
    for key, value in kwargs.iteritems()]
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/util.py", line 597, in _entity_descriptor
    return getattr(entity, key)
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/ext/hybrid.py", line 681, in __get__
    return self.expr(owner)
  File "/Users/Ben/Dropbox/Giraffe/giraffe_server/giraffe/model.py", line 133, in f_path
    print "\n\n\n[model.py:File@f_path hybrid_property] returning: ", os.path.join(env['project_dir'], self._f_path)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 66, in join
    if b.startswith('/'):
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/sql/expression.py", line 3426, in __nonzero__
    raise TypeError("Boolean value of this clause is not defined")
TypeError: Boolean value of this clause is not defined

最佳答案

您的混合属性必须返回一个 sql 表达式;你的没有,它返回一个 python 字符串。

要解决这种情况,不要在 python 中执行路径连接,而是在 SQL 表达式中执行:

return env['project_dir'] + os.path.sep + self._f_path

它将解析为 self._f_path.__radd__(result_of_project_dir_plus_os_path_sep),它既可以在查询中使用,也可以用作返回值。

关于python - 在 SQLAlchemy 中查询混合属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14504284/

相关文章:

python - Sympy:删除多项式中的高阶项

python - python 中的 Stroop 测试无法正常工作。

java - 在 JAR 中加载属性文件?

java - map 与类属性建议

python - 当实例分配给关系时,sqlalchemy before_flush 事件处理程序看不到外键的变化

python - 使用 SQLAlchemy 基于类自动构建数据库表

python - Django REST Framework 验证 slug 字段

python - 网页抓取空白返回 - 错误的元素

Python "callable"属性(伪属性)

python - 如何在普通类中使用相当于 __post_init__ 方法的方法?