SQLAlchemy:使用自定义字段和值构建查询

1 投票
2 回答
4267 浏览
提问于 2025-04-18 01:09

如何将下面的SQL查询转换成SQLAlchemy的形式?

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)

2 个回答

-4

你需要做的事情大概是这样的:

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的版本,但我相信这段内容是我记得的正确写法]

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)

撰写回答