When you need a computed attribute derived from existing columns — for example a discounted price calculated from the original price and a discount percentage — use SQLAlchemy’s hybrid_property instead of a plain @property. It behaves like a normal attribute on an instance, and it also works inside filter() and order_by() at the SQL level. That lets you filter and sort by the computed value without adding a column to the database or pulling the whole table into Python to filter by hand.
The Problem
Say you run a shop with a Product model that has two columns: price (original price) and discount (discount percentage). The final price is not worth storing as its own column because it changes every time price or discount changes. The natural approach is a @property:
class Product(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) price = db.Column(db.Integer, nullable=False) # original price (VND) discount = db.Column(db.Integer, default=0) # discount % @property def final_price(self): return self.price * (100 - self.discount) / 100
Reading one product’s price works fine: product.final_price returns the right amount. But the moment you want to list products discounted to under 100,000 VND, this query breaks:
db.session.query(Product).filter(Product.final_price < 100000).all()
SQLAlchemy raises TypeError: '<' not supported between instances of 'property' and 'int'. The reason: @property is only Python code, so the database has no idea what it is and cannot turn it into a WHERE condition. The usual workaround is to load every product and filter in Python — slow and memory-hungry once the table holds tens of thousands of rows.
The Solution
The fix is hybrid_property — a SQLAlchemy decorator that gives one attribute two “faces”: one for Python, one for SQL. You define the computation as usual, then add an .expression method that returns the equivalent SQL expression:
from sqlalchemy.ext.hybrid import hybrid_propertyclass Product(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False) price = db.Column(db.Integer, nullable=False) # original price (VND) discount = db.Column(db.Integer, default=0) # discount % @hybrid_property def final_price(self): return self.price * (100 - self.discount) / 100 @final_price.expression def final_price(cls): return cls.price * (100 - cls.discount) / 100
Accessed through an instance (product.final_price), SQLAlchemy runs the Python code just like a plain @property. But when you use it through the class inside filter() or order_by(), SQLAlchemy swaps in the SQL expression and produces exactly one SELECT ... WHERE statement. Verified with three sample products: filter(Product.final_price < 100000) returns only the “Mouse pad”, and order_by(Product.final_price) sorts by ascending price — all handled at the database layer, with no extra rows loaded into Python.
Apply It to Your Project
This pattern works for any value derived from columns of the same table: a full name joined from first_name and last_name, a line total computed from quantity * unit_price, or an in-stock flag derived from stock > 0. The rule of thumb is short: if you only need to display it, @property is enough; the moment you need to filter or sort by it in a query, switch to hybrid_property — and keep the Python logic and the SQL expression equivalent, or the filtered results will disagree with the displayed values.
Related Posts
- Flask: sửa lỗi N+1 query trong Flask-SQLAlchemy bằng joinedload và selectinload
- Flask: Define Relationships Correctly in Flask-SQLAlchemy — Two-Way Navigation in 5 Minutes
- Flask: Query in SQLAlchemy 2.0 Style with db.select() Instead of Model.query
Frequently Asked Questions
How is hybrid_property different from a plain @property?
@property only runs in Python, so it cannot be used in a query. hybrid_property adds an SQL expression, so the same attribute name can be read on an instance and used in filter() and order_by().
Do I need to add a column to the database or run a migration?
No. hybrid_property creates no new column — it is just a way to write the computation so SQLAlchemy can translate it into SQL. You need no migration and no schema change.
Must the SQL expression match the Python code exactly?
Yes, in terms of results. If the Python code divides by 100 while the SQL expression multiplies by 100, the filtered results will disagree with the displayed values. Write both versions to produce the same output for the same input, and verify them against a few sample rows before using them for real.
Does it work with Flask-SQLAlchemy 3.x and SQLAlchemy 2.0?
Yes. Import it from sqlalchemy.ext.hybrid and use it as shown here — this exact code was verified to run correctly on Flask 3.1, Flask-SQLAlchemy 3.1, and SQLAlchemy 2.1 with SQLite.
💬 Have you tried this in your own project? If you hit an error or have a neater way to do it, leave a comment below — I read them all and will add the best ideas to the post.
References
- SQLAlchemy Documentation — Hybrid Attributes: https://docs.sqlalchemy.org/en/20/orm/extensions/hybrid.html
- Flask-SQLAlchemy Documentation: https://flask-sqlalchemy.palletsprojects.com/
