这是原始问题的编辑版本,带有独立的示例。
from sqlalchemy import Column, Integer, String, create_engine, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
nickname = Column(String)
engine = create_engine('sqlite://', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base.metadata.create_all(engine)
session.add_all([
User(name='wendy', fullname='Wendy Williams'),
User(name='mary', fullname='Mary Contrary'),
User(name='fred', fullname='Fred Flintstone', nickname='freddy')])
session.commit()
items = session.query(
User.id, User.name,
func.coalesce(User.nickname, 'Nicky').label('nickname'))
# Checking that with_entities works on original data set
subset_items = session.query(
User.id, User.name)\
.with_entities(User.name, User.nickname)\
.all()
print(subset_items)
# items will be used elsewhere....
# Wanted: a subset with columns fullname and nickname only
# Result is wrong, it does not use coalesce result
special_items = items\
.with_entities(User.fullname, User.nickname) \
.all()
print(special_items)
如何使用.with_entities引用项目?以下失败
.with_entities(items.fullname, items.nickname) \
@Nick在回答原始问题时也使用带引号的变体。
答案 0 :(得分:0)
我还没有测试过,但是我相信您应该可以use a string here而不是表达式:
.with_entities('pat_no') \
答案 1 :(得分:0)
由于没有任何回复,因此我将其发布在SQLAlchemy的社区站点上。答案出奇地尴尬:
q = q.with_entities(q.column_descriptions[1]['expr'], q.column_descriptions[2]['expr'])