Opened 6 years ago

Closed 6 years ago

#29526 closed Uncategorized (invalid)

Use of QuerySet.extra() when excluding twice a string occurance

Reported by: Manuel Strehl Owned by: nobody
Component: Uncategorized Version: 2.0
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

The documentation told me to open this bug :-)

My use case for .extra() is a query, where I have to filter for a certain term but need to exclude objects, where the term appears twice:

MyModel.object.filter(namecontains=term).extra(where=name NOT LIKE %s, params=['{}%{}'.format(term, term)])

One possibility to remove the need for .extra() in my case would be, if one could opt-out of the % escaping in .filter() and .exclude():

....exclude(namecontains=term+'%'+term, keep_placeholders=True)

Change History (1)

comment:1 by Simon Charette, 6 years ago

Resolution: invalid
Status: newclosed

Hey Manuel,

I suggest you have a look at the custom lookup documentation.

You should be able to achieve what you're after by defining a custom Like lookup and registering on CharField and TextField.

from django.db import models

class Like(models.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

models.CharField.register_lookup(Like)
models.TextField.register_lookup(Like)

Then it would be a simple matter of using it in your exclude() call

exclude(name__like='{}%{}'.format(term, term))
Note: See TracTickets for help on using tickets.
Back to Top