SELECT UNCOMPRESS(text) FROM with sqlalchemy

最后都变了- 提交于 2020-01-02 23:21:32

问题


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

( mysql Compress() with sqlalchemy )

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)

but this does not work. It returns an sqlalchemy.sql.expression.Function and not the string.

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.


回答1:


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 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))

Now whenever SQLAlchemy loads an instance from the database, the SELECT query will contain SELECT ..., UNCOMPRESS(demotable.data), ... FROM demotable.

Edit by Giorgos Komninos: I used the

http://docs.sqlalchemy.org/en/rel_0_7/orm/mapper_config.html#using-a-plain-descriptor

and it worked.



来源:https://stackoverflow.com/questions/11411681/select-uncompresstext-from-with-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!