在 SQLAlchemy 中查询混合属性

编程入门 行业动态 更新时间:2024-10-23 19:27:54
本文介绍了在 SQLAlchemy 中查询混合属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm storing file paths as relative paths in the database, but I'm then using hybrid properties to turn in into an absolute path when its mapped. When I query using this property it throws an error. Here's the model:

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 字符串):

When I run this query (where ref is a unicode string):

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 字符串.

Your hybrid property must return a sql expression; yours does not, it returns a python string instead.

为了解决这个问题,不要在 python 中进行路径连接,而是在 SQL 表达式中:

To resolve that for this case, don't do the path join in python but in a SQL expression instead:

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

将解析为 self._f_path.__radd__(result_of_project_dir_plus_os_path_sep),既可用于查询,也可用作返回值.

which will resolve to self._f_path.__radd__(result_of_project_dir_plus_os_path_sep), which can be used both in queries and as a return value.

更多推荐

在 SQLAlchemy 中查询混合属性

本文发布于:2023-10-18 11:14:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504078.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   SQLAlchemy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!