使用sqlalchemy从中选择UNCOMPRESS(text) [英] SELECT UNCOMPRESS(text) FROM with sqlalchemy
问题描述
我存储MySQL Compress函数以将压缩的Blob数据插入数据库.
I store the MySQL Compress function to insert compressed blob data to the database.
在上一个问题中,我被指示使用
In a previous question I was instructed to to use
func.compress
(带有sqlalchemy的mysql Compress())
现在的问题是我还想从数据库中读取数据. 在mysql中,我会做完
The problem now is that I want to read also the data from the database. In mysql I would have done
SELECT UNCOMPRESS(text) FROM ...
可能我应该在课堂上使用吸气剂. 我尝试做类似的事情:
probably I should use a getter in the class. I tried to do somethin like:
get_html(self):
return func.uncompress(self.text)
但是这不起作用.它返回一个sqlalchemy.sql.expression.Function而不是字符串.
but this does not work. It returns an sqlalchemy.sql.expression.Function and not the string.
此外,我找不到哪个函数包含sqlalchemy的func.
Moreover I could not find which functions contains sqlalchemy's func.
关于如何在对象中编写吸气剂,以便获取未压缩数据的任何想法.
Any ideas on how i could write a getter in the object so I get back the uncompressed data.
推荐答案
func
实际上是用于特殊功能对象的真正精美的工厂对象,这些特殊功能对象在查询时呈现给SQL-您无法在Python中对其进行评估,因为Python不会对它们进行评估了解数据库如何实现compress()
.这就是为什么它不起作用.
func
is actually a really fancy factory object for special function objects which are rendered to SQL at query time - you cannot evaluate them in Python since Python would not know how your database implements compress()
. That's why it doesn't work.
SQLAlchemy允许您将 SQL表达式映射到映射的类属性.如果您使用的是声明性语法,请像这样扩展您的类(未经测试,但我相信这是可行的方法):
SQLAlchemy lets you map SQL expressions to mapped class attributes. If you're using the declarative syntax, extend your class like so (it's untested, but I'm confident this is the way to go):
from sqlalchemy.orm import column_property
class Demo(...):
data_uncompressed = column_property(func.uncompress(data))
现在,每当SQLAlchemy从数据库加载实例时,SELECT查询将包含SELECT ..., UNCOMPRESS(demotable.data), ... FROM demotable
.
Now whenever SQLAlchemy loads an instance from the database, the SELECT query will contain SELECT ..., UNCOMPRESS(demotable.data), ... FROM demotable
.
由Giorgos Komninos 我用
Edit by Giorgos Komninos: I used the
http://docs.sqlalchemy. org/en/rel_0_7/orm/mapper_config.html#using-a-plain-descriptor
它奏效了.
这篇关于使用sqlalchemy从中选择UNCOMPRESS(text)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!