Skip to content

Instantly share code, notes, and snippets.

@RussellLuo
Created July 17, 2014 03:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save RussellLuo/ad344b4fa1295bcc282c to your computer and use it in GitHub Desktop.
Save RussellLuo/ad344b4fa1295bcc282c to your computer and use it in GitHub Desktop.
An example showing how to use @hybrid_property in SQLAlchemy.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from sqlalchemy.ext.hybrid import hybrid_property
Base = declarative_base()
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
fake_pv = Column(Integer, default=0)
actual_pv = Column(Integer, default=0)
@hybrid_property
def pv(self):
"""Use `fake_pv` if it's configured, otherwise, use `actual_pv`."""
# Caution:
# TypeError("Boolean value of this clause is not defined")
# will be raised if the next line is rewritten as
# "if self.fake_pv > 0:"
if (self.fake_pv > 0) is True:
return self.fake_pv
else:
return self.actual_pv
def get_pop_posts(session):
session.query(Post).order_by(Post.pv.desc())
if __name__ == '__main__':
posts = get_pop_posts(Session())
print(posts)
@cisko3000
Copy link

Hey, thanks for posting this. It pointed me in the right direction, but I still had some problems and that's when I came across this:
http://docs.sqlalchemy.org/en/latest/orm/mapped_sql_expr.html
It says some hybrid properties need to exist alongside a SQL expression constructor in order to work well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment