I'm using a hybrid_property to generate a calculated property that indicates if an article is published based on its scheduled publish date and whether or not it "is_published":
class Article(db.Model):
__tablename__ = 'articles'
id = db.Column(db.Integer, primary_key=True)
publish_date = db.Column(db.DateTime, index=True)
is_published = db.Column(db.Boolean,index=True,default=False)
def __repr__(self):
return '<Article {}>'.format(self.id)
@hybrid_property
def published(self):
"""Returns true if the publish date is at or before the current time and is_published is true."""
return self.is_published and self.publish_date <= datetime.now()
Given the following set of articles:
Article 1: Publish date: 2020-5-12 is_published: True
Article 2: Publish date: 2020-5-13 is_published: False
I can perform the following check:
>>> Article.query.all()[0].published
True
>>> Article.query.all()[1].published
False
But when querying, the filter returns as if the value were true for this calculated field for all articles:
>>> Article.query.filter_by(published=False).all()
[]
>>> Article.query.filter_by(published=True).all()
[<Article 1>, <Article 2>]
Am I doing something wrong? Is there a better way to quickly and easily filter by this basic calculation?