简体   繁体   中英

Using regex on Charfield in Django

I have a model with

class dbf_att(models.Model):
    name = models.CharField(max_length=50, null=True)

And i'd like to check later that object.name match some regex:

    if re.compile('^\d+$').match(att.name):
        ret = 'Integer'
    elif re.compile('^\d+\.\d+$').match(att.name):
        ret = 'Float'
    else:
        ret = 'String'
  return ret

This always return 'String' when some of the att.name should match those regex.

Thanks!

You can try with RegexValidator

Or you can to it with package django-regex-field , but i would rather recommand you to use built-in solution, the less third-party-apps the better.

Regex are great, but sometimes it is more simpler and readable to use other approaches. For example, How about just using builtin types to check for the type

try:
    att_name = float(att.name)
    ret = "Integer" if att_name.is_integer() else "Float"
except ValueError:
    ret = "String"

FYI, your regex code works perfectly fine. You might want to inspect the data that is being checked.

Demo:

>>> import re
>>> a = re.compile('^\d+$')
>>> b = re.compile('^\d+\.\d+$')
>>> a.match('10')
<_sre.SRE_Match object at 0x10fe7eb28>
>>> a.match('10.94')
>>> b.match('10')
>>> b.match('10.94')
<_sre.SRE_Match object at 0x10fe7eb90>
>>> a.match("string")
>>> b.match("string")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM