开发者

Django query phone numbers excluding brackets

I am trying to build a django query that filter开发者_JAVA百科s phone numbers (CharField) but excludes brackets

eg.

if I search for 0123456789 it would find (01) 234 567 89

Thanks


Well, you can either use regex, or you can reformat your search:

pn = '0123456789'
Model.objects.filter(phone='(%s) %s %s %s' % (pn[:2], pn[2:5], pn[5:8], pn[8:]))

Ideally you normalize all phone numbers and you'd search for them in that format. If you check out django.contrib.localflavors.us's PhoneNumberField, it forces all new phone numbers to be saved in XXX-XXX-XXXX format, for instance. If you aren't normalizing the phone numbers somehow, you should be. Dealing with multiple potential formats would not be fun.


You can also use regular expressions in your lookup. See: https://docs.djangoproject.com/en/dev/ref/models/querysets/#s-regex


I never like to answer my own questions, but this solution might be helpful to others doing a similar thing:

I defined a function on the model using the @property decorator.

class MyModel(models.model):
    ....
    phoneNumber = CharField...

    @property
    def raw_phone_number(self):
        # function strips those characters and returns just the number
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜