简体   繁体   中英

SQLAlchemy filter_by json column

I have model like this:

class Customer(Base):
__tablename__ = 'customers'
uuid = database.Column(database.String, primary_key=True)
activity_type = database.Column(database.String)
activity = database.Column(database.JSON)

I need to filter_by activity_type and also activity like this:

@staticmethod
def create_if_not_exist(customer):
    """ Create customer if not exists """
    if Customer.query.filter_by(
            activity_type=customer.activity_type,
            activity=customer.activity
    ).first() is None:
        customer.save()

    return customer.uuid

If doesnt work for json colum activity. Can someone help me how to filter_by json column ?

One PostgreSQL specific solution to this is to utilize PostgreSQLs JSONB column:

from sqlalchemy.dialects.postgresql import JSONB

class Customer(Base):
    __tablename__ = 'customers'
    uuid = database.Column(database.String, primary_key=True)
    activity_type = database.Column(database.String)
    activity = database.Column(JSONB)

Your original query should then evaluate properly.

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