如何将以下SQL查询转换为SQLAlchemy analog?
SELECT 'custom_value' AS `custom_field`, f.`bar` FROM `Foo` f
'Foo'模特:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class Foo(Base):
__tablename__ = 'Foo'
id = Column(Integer, primary_key=True)
bar = Column(String)
答案 0 :(得分:2)
请看这个答案中的第二个例子:https://stackoverflow.com/a/3576573/344141
简而言之 - 使用literal("custom_value", type_=Unicode).label('custom_field')
,因此您的查询将如下所示:
session.query(literal("custom_value", type_=Unicode).label('custom_field'), Foo.bar)
答案 1 :(得分:-2)
你需要做的是这样的事情:
from sqlalchemy.engine import create_engine
from sqlalchemy.orm import sessionmaker, mapper
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class Foo(Base):
__tablename__ = 'Foo'
id = Column(Integer, primary_key=True)
bar = Column(String)
engine = create_engine(connection_string, echo=False)
Session = sessionmaker(bind=engine)
db = Session()
# Results
qu = select([Foo.custom_field.label('custom_value'), Foo.bar])
results = db.query(qu).all()
[注意 - 我不接近Python的版本,但相信这是我的记忆中的正确