Pav Sidhu
Pav Sidhu

Reputation: 6944

Automatically setting the value of a field based on another with 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

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.

Upvotes: 3

Views: 1466

Answers (1)

Pav Sidhu
Pav Sidhu

Reputation: 6944

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)

Upvotes: 3

Related Questions