C
C
Cross58202020-03-12 10:34:52
Python
Cross5820, 2020-03-12 10:34:52

How to do search by first letter in psycopg2 and python?

I decided to write a simple application for accounting for the consumption of components (all for myself).
I wanted to do a search so that names are pulled into the application table.
Wrote the following:
cur.execute("select id from Components where ComponentName ilike %s group by Components.id;", [search])

However, this solution searches by the full name (which is logical). In psql itself, I know how to search by the first letter, but I have no idea how it looks in psycopg2. Reading the documentation did not help, it just describes the search with the full name. In general, once again the essence, what and how should I use / write in order to search by the first letter?

PS I don't have much programming experience, sorry!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2020-03-12
@Cross5820

Try something like this:
by substring

cur.execute(
    "select id from Компоненты where Наименование_компонента ilike %s group by Компоненты.id;",
    [f'%{search}%']
)

or by letter
cur.execute(
    'select id from Компоненты where left (Наименование_компонента, 1) = %s  group by Компоненты.id;', 
   [search]
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question