首页 > 解决方案 > 如何按子字符串过滤 JSONB 字段(SQLAlchemy、Postgresql)

问题描述

我想使用 SQLAlchemy 过滤包含子字符串的 JSONB 字段。

我知道我可以使用 contains() 找到完全相同的键,但我想找到该键的子字符串。就像使用带有文本字段的 ilike() 一样。我想对列、收件人和参数都这样做。但是,如果我会得到帮助,我会在第二列中找出如何做到这一点。

class NotificationMixin:

    id = Column(Integer, primary_key=True)
    recipient = Column(JSONB, nullable=False)
    params = Column(JSONB, default={})

class EmailResource(AdminDataTableResource):

    def _apply_filters(self, emails, filters):
        for key in filters.items():
            f_name = key[0]
            f_val = key[1]
            if len(f_val) > 0:

                if f_name == 'recipient':
                    emails = emails.filter(Email.recipient.contains('"' + f_val + '"'))

                if f_name == 'shipment_number':
                    emails = emails.filter(Email.params["shipment_number"].contains('"' + f_val + '"'))

我可以使用 contains() 以某种方式表现得像 ilike() 吗?如果没有,在我的情况下如何过滤子字符串?有任何想法吗?

标签: pythonjsonpostgresqlfiltersqlalchemy

解决方案


推荐阅读