Python SQLAlchemy:使用自定义字段和值构建查询
如何将下面的SQL查询转换为SQLAlchemy模拟Python SQLAlchemy:使用自定义字段和值构建查询,python,sqlalchemy,Python,Sqlalchemy,如何将下面的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):
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)
您需要做的是这样的事情:
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的版本,但从我的记忆中,我相信这是正确的看看这个答案中的第二个例子: 简而言之,使用
literal(“自定义值”,键入Unicode)。label(“自定义字段”)
,因此您的查询如下所示:
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()
session.query(literal(“自定义值”,类型=Unicode).label(“自定义字段”),Foo.bar)
这似乎是错误的。AttributeError:type对象“Foo”没有“custom\u field”属性。很抱歉,这是错误的。但是有人说我不接近Python的副本……因此无法保证正确性。custom\u field
是什么?它来自哪里?它只是自定义的“手工”字段。如何导入函数文本?