使用SQLAlchemy自动设置基于另一个字段的值 [英] Automatically setting the value of a field based on another with SQLAlchemy
本文介绍了使用SQLAlchemy自动设置基于另一个字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Flask-SQLAlchemy,我有一个看起来像这样的表:
Using Flask-SQLAlchemy I have a table which looks like this:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
slug = db.Column(db.String(200), nullable=False)
def __init__(self, name):
self.name = name
我有一个 Python库,它可以将某些文本的值转换为类似 slugify('Hello World')
到 hello-world
.
I have a Python library which converts the value of some text into a slug like slugify('Hello World')
to hello-world
.
说我要创建一个用户:
user = User('John Smith')
db.session.add(user)
db.session.commit()
我希望 User
表中的 slug
的值是 Slugify('John Smith')
.
我将如何处理?谢谢.
推荐答案
正如IanAuld在评论中所说,我应该像这样添加 self.slug = slugify(name)
:
As IanAuld said in the comments I should just add self.slug = slugify(name)
like so:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
slug = db.Column(db.String(200), nullable=False)
def __init__(self, name):
self.name = name
self.slug = slugify(name)
这篇关于使用SQLAlchemy自动设置基于另一个字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文