how to handle sqlalchemy onupdate when current context is empty?

后端 未结 1 911
无人及你
无人及你 2021-01-14 03:02

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         


        
相关标签:
1条回答
  • 2021-01-14 03:22

    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
    
    0 讨论(0)
提交回复
热议问题