vandelay vandelay - 1 month ago 9
Python Question

Query search. Return a list of results instead of just the first. By prefix substring

I'm trying to get all objects which has the searchWord as a substring, in the column symbol.

if the searchWord is G, and there's five stock objects that exist:

GOOG
APPL
FLO.CO
GARY
OEGP


Then I'd like to retrieve
GOOG
and
GARY
but not
OEGP
. Just the prefix substring

Below is a scrap of code I've tried. But it'll just return one object.

results = stock.objects.all().filter(symbol=searchWord)

for x in results:
print(x.symbol)

Answer

You may use startswith with QuerySet.filter(). Your ORM query should be as:

results = stock.objects.all().filter(symbol__startswith=searchWord)

This will check for the case-sensitive searchWord as prefix for the values in symbol coloumn. In case you want to do case-insensitive prefix check, use istartswith instead.

Comments