I'm trying to add a "slug" field to my db.Model class Post, in which it takes the title of the post and returns it in a better format for a URL.
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(64), index=True, unique=True)
body = db.Column(db.Text)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Post {}>'.format(self.title)
@hybrid_property
def slug(self):
result = []
punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
for word in punct_re.split(self.title.lower()):
if word:
result.append(word)
return '-'.join(result)
I can reference the slug by Post.slug, but when I try to query it, as Post.query.filter_by(slug='test-slug-1'), I get the message
sqlalchemy.exc.InvalidRequestError: Entity <class 'app.models.Post'> has no property 'slug'
From what I understand I need a hybrid expression, but the examples I've seen have made it more confusing. Any ideas on how to filter by the hybrid property slug, or am I going about generating this slug incorrectly?