问题
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