2015-11-14 59 views
2

我有文章將基於它的標題有塞的模式,這個模式是這樣的:如何在當前上下文爲空時處理sqlalchemy onupdate?

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正在稱號的價值。所以,每當文章slug將匹配它的標題。但是,當我編輯的內容,而不改變它的標題,這 引發異常

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

我想這是因爲current_params不包含title。如果,我在那裏更改 lambda並使用if,slu will將爲None。那麼我怎樣才能處理 這個並保持slug值與它的標題相匹配?

回答

5

可以使用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 

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 
相關問題