Consider the following sqlalchemy model that validates the primary_email field:
from sqlalchemy import Column, String
from sqlalchemy.orm import validates
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects import postgresql
from sqlalchemy.ext.mutable import MutableList
Base = declarative_base()
class Test(Base):
id = Column(Integer, primary_key=True)
primary_email = Column(String(128))
@validates('primary_email')
def valid_email(self, key, value):
if not '@' in value:
raise ValueError(f"Invalid {key}: '{value}'")
return value
def __init__(self, email):
primary_email = email
It works as expected but now I want to add another column
secondary_email = Column(MutableList.as_mutable(postgresql.ARRAY(String(128))))
How do I perform validation on secondary_email.append(email) call?
When I add 'secondary_email' to validates decorator, it only gets triggered on assignment operations like
self.secondary_email = ['example@me.com']
I believe this is something that can be achieved with a custom class but I wonder if there is a simpler and more generic solution?