Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

python - how to handle sqlalchemy onupdate when current context is empty?

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 sqlalchemy import Column, Integer, String, Text

Base = declarative_base()


class Article(Base):

    __tablename__ = 'article'

    id = Column(Integer, primary_key=True)
    title = Column(String(100), nullable=False)
    content = Column(Text)
    slug = Column(String(100), nullable=False,
                  default=lambda c: c.current_params['title'],
                  onupdate=lambda c: c.current_params['title'])

slug is taking title's value. So, everytime article slug will match it's title. But, when I edit the content without changing it's title, this exception is raised

(builtins.KeyError) 'title' [SQL: 'UPDATE article SET content=?, slug=?,
updated_at=? WHERE article = ?'] [parameters: [{'article_id': 1,
'content': 'blah blah blah'}]]

I guess that because current_params doesn't contain title. If, I change the lambda there and using if, slug will be None. So how can I handle this and keep the slug value match it's title?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...