我有一个基于它的标题的文章模型,模型是这样的:
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
,slug将是None
。那我该怎么办?
这和slug值保持匹配吗?
答案 0 :(得分:5)
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
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