Automatically setting the value of a field based on another with SQLAlchemy

孤人 提交于 2020-01-06 02:46:06

问题


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

I have a Python library which converts the value of some text into a slug like slugify('Hello World') to hello-world.

Say I was to create a User:

user = User('John Smith')
db.session.add(user)
db.session.commit()

I would like the value of slug in the User table to be Slugify('John Smith').

How would I go about this? Thanks.


回答1:


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)


来源:https://stackoverflow.com/questions/32289442/automatically-setting-the-value-of-a-field-based-on-another-with-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!