Opened 7 years ago

Closed 7 years ago

#27429 closed New feature (duplicate)

had to use QuerySet.extra to do WHERE LIKE with arbitrary amount / placement of wildcard characters

Reported by: Lance Robertson Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: QuerySet.extra
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Lance Robertson)

My use case is that I'm trying to find phonetic patterns that rhyme using a database I built from the pronunciation dictionary CMUdict

For example:

Pronunciation.objects.extra(where=["code LIKE '%% - %%__1 - S T __0 D'"])

I want to be able to filter with % and _ wildcards in arbitrary amounts and places in the search string beyond just contains, startswith, and endswith, and the only way I could figure out how to do it is either to use a raw query or .extra - if .extra goes away I hope filter will support this behavior!

Change History (2)

comment:1 by Lance Robertson, 7 years ago

Description: modified (diff)

comment:2 by Simon Charette, 7 years ago

Component: UncategorizedDatabase layer (models, ORM)
Resolution: duplicate
Status: newclosed
Type: UncategorizedNew feature
Version: 1.10master

It was decided that we were not going to add like and ilike lookups in #17473.

Now that custom lookups are available you can define your own LIKE implementation as follow:

from django.db.models import CharField, Lookup, TextField

class LikeLookup(Lookup):
    lookup_name = 'like'

    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        rhs, rhs_params = self.process_rhs(compiler, connection)
        params = lhs_params + rhs_params
        return '%s LIKE %s' % (lhs, rhs), params

CharField.register_lookup(LikeLookup)
TextField.register_lookup(LikeLookup)

And use like that

Pronunciation.objects.filter(code__like='%% - %%__1 - S T __0 D')
Note: See TracTickets for help on using tickets.
Back to Top