foobarbecue
foobarbecue

Reputation: 7060

Django queryset to find entries in all capital letters?

In raw SQL, it is possible to look through a database to find rows with a column for which the contents are written in all capital letters; that question was answered here.

Is there a way to accomplish the same thing using the Django ORM and without resorting to .raw() ?

Upvotes: 0

Views: 2316

Answers (2)

Anurag
Anurag

Reputation: 3114

You can use regular expression match in Django ORM. Link to documentation - https://docs.djangoproject.com/en/dev/ref/models/querysets/#iregex

Example:

Entry.objects.get(title__regex=r'^(An?|The) +')

SQL equivalents:

SELECT ... WHERE title REGEXP BINARY '^(An?|The) +'; -- MySQL

SELECT ... WHERE REGEXP_LIKE(title, '^(an?|the) +', 'c'); -- Oracle

SELECT ... WHERE title ~ '^(An?|The) +'; -- PostgreSQL

SELECT ... WHERE title REGEXP '^(An?|The) +'; -- SQLite

Using raw strings (e.g., r'foo' instead of 'foo') for passing in the regular expression syntax is recommended.

EDIT: You can add the regular expression like:

Entry.objects.get(title__regex=r'^[[:upper:]]+$') #not tested

Upvotes: 2

foobarbecue
foobarbecue

Reputation: 7060

Figured it out. Looks like the best way is to use extra. For example,

MyModel.objects.extra(where=['title = UPPER(title)'])

Upvotes: 2

Related Questions