2

According to Django docs

Entry.objects.get(headline__contains='Lennon')

Roughly translates to this SQL:

SELECT ... WHERE headline LIKE '%Lennon%';

But if I want to do somethng like this (removing a wildcard):

SELECT ... WHERE headline LIKE '%Lennon';

What would the Django query be?

O James
  • 189
  • 1
  • 12

1 Answers1

1

The keywords for partial field lookups you are looking for are startswith and endswith:

Entry.objects.filter(headline__startswith='Lennon')
Entry.objects.filter(headline__endswith='Lennon')

You can also use the case insensitive variants, istartswith and iendswith:

Entry.objects.filter(headline__istartswith='lennon')
Entry.objects.filter(headline__iendswith='lennon')
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Django covers trivial cases. It would be great to cover something like `...LIKE 'foo_bar%baz%'` '_' match any 1 character and ' %' used in the middle of the word – hipertracker Feb 02 '20 at 13:35
  • 2
    @hipertracker You can use a regex search for more complex cases: `Entry.objects.filter(headline__regex='^foo_bar.*baz.*$')`. According to [the Django devs](https://code.djangoproject.com/ticket/17473) the performance penalty is negligible for PostgreSQL. – Selcuk Feb 02 '20 at 14:57