[Answered ]-How do I find all instances that have field: "username" inequivalent to its stripped "username"

1πŸ‘

βœ…

Why are you storing usernames in your database with leading and trailing spaces? Trim them before you insert them instead of allowing dirty data in your database.

But to answer your question directly, you don’t need to use extra to do a regular expression lookup, as the queryset API natively supports it.

This should do what you want:

User.objects.filter(username__regex=r"\s*" + user + r"\s*")

Things get a little messy on SQLLite, where regex lookups aren’t natively supported, but it still works.

πŸ‘€Brett Gmoser

1πŸ‘

extra can be used. This is what it would look like for PostgreSQL:

User.objects.extra(where=["username != regexp_replace(username, '^\s+|\s+$', '', 'g')"])
πŸ‘€Adrian Ghiuta

0πŸ‘

from django.db.models import Q

User.objects.filter(Q(username__startswith=' ') | Q(username__endswith=' '))
πŸ‘€madzohan

Leave a comment