Habel
Habel

Reputation: 59

Django ORM: Compare substring

Is there a way to compare the last 10 characters of a column (type string) in database using django ORM query. I want to do something like:

foo = '1234567890'
result= db.objects.filter(col1[-10:]=foo).values('name')

But col1[-10:] doesn't work. Is there any alternative for this?

Note: foo can be less than 10 characters and we want to match the last characters or maximum possible characters. foo='67890' shouldn't match '1234567890' but only '67890'. However, foo='1234567890' should match '991234567890'.

Upvotes: 1

Views: 1263

Answers (1)

Visgean Skeloru
Visgean Skeloru

Reputation: 2263

Use django endswith filter: https://docs.djangoproject.com/es/1.9/ref/models/querysets/#std:fieldlookup-endswith

model.objects.filter(col1__endswith=foo).values('name')

What you have tried would raise SyntaxError.

Upvotes: 3

Related Questions