Home > other >  Django filter queryset for replacing charactors
Django filter queryset for replacing charactors

Time:04-06

I have a customer table with masked phone numbers (944 (543) 3556) stored in it. (field: phone).

I want to filter/search the table using phone number without any special charactors. I tried below filter queries and it is not return expecting results.

self.queryset = self.queryset.annotate(customer_phone=Value(re.sub('[^0-9]','','123@#'),output_field=models.CharField()))
print ('customer_phone:', self.queryset[0].customer_phone) 

# Output: customer_phone: 123 [Expected result]

But when I give field name, it returns following error.

self.queryset = self.queryset.annotate(customer_phone=Value(re.sub('[^0-9]','',F('phone')),output_field=models.CharField()))
print ('customer_phone:', self.queryset[0].customer_phone)

File "/usr/local/lib/python3.6/re.py", line 191, in sub
backend_1        |     return _compile(pattern, flags).sub(repl, string, count)
backend_1        | TypeError: expected string or bytes-like object

Is there anyway to filter phone number without considering the special charactors in it?

python version: Python 3.6.5 Django==2.0.1

CodePudding user response:

Try this query:

from django.db.models import Func
self.queryset.objects.annotate(customer_phone=Func(F('phone'), Value('[^0-9]'), Value(''), Value('g'), function='REGEXP_REPLACE', output_field=models.CharField()))
  • Related