简体   繁体   中英

Can I compare the json data of one column to another in Flask Sqlalchemy?

I'm using flask Sqlalchemy with a Postgres db and I'm trying to filter to find all the instances of a model where 1 string value of a json data column is equal to another (UUID4) column.

class MyModel (db.Model):
id = db.Column(UUID(as_uuid=True), primary_key=True,
                   index=True, unique=True, nullable=False,
                   server_default=sa_text("uuid_generate_v4()"))
site = db.Column(UUID(as_uuid=True), db.ForeignKey(
        'site.id'), index=True, nullable=False)
data = db.Column(JSON, default={}, nullable=False)

and these models' data column looks like

{
    "cluster": "198519a5-b04a-4371-b188-2b992c25d0ae",
    "status": "Pending"
}

This is what I'm trying:

filteredModels = MyModel.query.filter(MyModel.site == MyModel.data['cluster'].astext)

I get:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedFunction) operator does not exist: uuid = text
LINE 4: ...sset.type = 'testplan' AND site_static_asset.site = (site_st...
                                                             

HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

The error message is telling you that Postgresql doesn't have a way to directly compare UUIDs with text values. In other words, it cannot process

MyModel.site == MyModel.data['cluster'].astext

To get around this, you need to cast one side of the comparison to be the same type as the other. Either of these should work:

from sqlalchemy import cast, String

MyModel.query.filter(cast(MyModel.site, String) == MyModel.data['cluster'].astext)

MyModel.query.filter(MyModel.site == cast(MyModel.data['cluster'].astext, UUID))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM