I have a model of article which will have slug based on it\'s title, the model is like this:
from sqlalchemy.ext.declarative import declarative_base
from sql
You can use validates() decorator:
from sqlalchemy.orm import validates
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.String)
slug = db.Column(db.String(100), nullable=False)
@validates('title')
def update_slug(self, key, title):
self.slug = title
return title
Or events:
from sqlalchemy import event
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.String)
slug = db.Column(db.String(100), nullable=False)
@event.listens_for(Article.title, 'set')
def update_slug(target, value, oldvalue, initiator):
target.slug = value