Field validation

209 views
Skip to first unread message

Alec Taylor

unread,
Feb 19, 2015, 10:09:08 AM2/19/15
to peewe...@googlegroups.com
How do I customise field validation in peewee?

In other ORMs it's possible:

SQLalchemy: http://docs.sqlalchemy.org/en/rel_0_9/orm/mapped_attributes.html
Storm: https://storm.canonical.com/Manual#Common_constructor_parameters
Django's ORM: https://docs.djangoproject.com/en/1.7/howto/custom-model-fields/

So I'm sure it's possible in peewee also.

Maybe related to this? -
http://peewee.readthedocs.org/en/latest/peewee/models.html#creating-a-custom-field

An example (would probably use validate_email package in prod):
from email.utils import parseaddr

class Email(Field):
def db_value(self, value):
email = parseaddr(value)[1]
assert '@' in value and parseaddr
return email

Also if db fields had a declarative syntax that would be very useful,
e.g.: autogenerating validation from json-schema like with:
https://github.com/topliceanu/mongoose-gen. I'm sure I could hack
together a code-generator, but that would be less useful than dynamic
support.

Alec Taylor

Charles Leifer

unread,
Feb 19, 2015, 5:28:30 PM2/19/15
to peewe...@googlegroups.com
To keep peewee lightweight I did not add validations. You can add them by overriding the `save()` method or howsoever you choose.


Alec Taylor

--
You received this message because you are subscribed to the Google Groups "peewee-orm" group.
To unsubscribe from this group and stop receiving emails from it, send an email to peewee-orm+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Alec Taylor

unread,
Mar 8, 2015, 7:33:09 AM3/8/15
to peewe...@googlegroups.com
I did this, but I'm not impressed:

class EmailField(CharField):
def coerce(self, value):
# In production, recommend using: `validate_email(value,
check_mx=True, verify=True)`
assert validate_email(value), 'Expected a valid email from:
"{value}"'.format(value=value)
return super(CharField, self).coerce(value)
Reply all
Reply to author
Forward
0 new messages