vandelay
vandelay

Reputation: 2065

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)

Upvotes: 0

Views: 70

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

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 column. In case you want to do case-insensitive prefix check, use istartswith instead.

Upvotes: 2

Tammo Heeren
Tammo Heeren

Reputation: 2104

Maybe list comprehension works for you (corrected).

results = [r for r in results if r.startswith(searchWord)]

Upvotes: 0

Related Questions