用于替换字符的 Django 过滤器查询集

Django filter queryset for replacing charactors

我有一个客户 table,其中存储了屏蔽的 phone 号码 (944 (543) 3556)。 (字段:phone)。

我想 filter/search table 使用 phone 没有任何特殊字符的号码。我尝试了下面的过滤器查询,它不是 return 预期的结果。

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]

但是当我给出字段名称时,return出现以下错误。

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

有没有办法过滤掉phone号而不考虑其中的特殊字符?

python版本:Python3.6.5 Django==2.0.1

试试这个查询:

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()))