gpt4 book ai didi

python - 当前上下文为空时如何处理sqlalchemy onupdate?

转载 作者:太空宇宙 更新时间:2023-11-03 14:15:30 26 4
gpt4 key购买 nike

我有一个文章模型,它会根据它的标题有 slug,模型是这样的:

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 正在获取 title 的值。因此,每次文章 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 值匹配它的标题?

最佳答案

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

关于python - 当前上下文为空时如何处理sqlalchemy onupdate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33708219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com