Created
July 17, 2014 03:53
-
-
Save RussellLuo/ad344b4fa1295bcc282c to your computer and use it in GitHub Desktop.
An example showing how to use @hybrid_property in SQLAlchemy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.