How to ignore case when filter value in database with python

603 Views Asked by At

I've tried to find an answer of my question.

And I find some answers but I don't know how to apply those to my question.

I'm using flask sqlalchemy.

This is my python code for getting product list.

def get_products(cls, request):
    with gshop.session_scope() as session:

        products = session.query(Product.id,
                                 Product.product_name,
                                 Product.logo_img_id,
                                 Product.product_cat_id,
                                 Product.display_no,
                                 Product.brand_id)

        if 'query' in request:
            query = json.loads(request['query'])
            filters = query['filters']
            for key, value in filters.items():
                try:
                    products = products.filter(getattr(Product, key).like("%" + str(value) + "%"))
                except AttributeError:
                    pass

'request' parameter is the 'param' from http request of client.

print(request) looks like this.

{
    'query': '{
        "filters":{
            "product_name":"aBcDeFgH"
        }
    }
}

When I tried to search product by name 'aBcDeFgH',

I want to get all data which includes this keyword with ignoring case.

How can I do this?

If you have any link or idea, just throw that to me.

Then I'll try a new way with referenced.

Thanks in advance, and Happy New Year. :)

1

There are 1 best solutions below

0
On

I'm really sorry for my googling ability..

This was a kind of simple thing.

Case Insensitive Flask-SQLAlchemy Query

This link gave a perfect answer for this silly question.

Here's an solution sample.

Original code

products = products.filter(getattr(Product, key).like("%" + str(value) + "%"))

Solved code

products = products.filter(getattr(Product, key).ilike("%" + str(value) + "%"))

Only just change like to ilike.