SQLAlchemy声明。指定要选择的列

时间:2012-04-30 17:12:27

标签: python sqlalchemy

声明性基础:

Base = declarative_base()
Base.query = Session.query_property()

班级:

class Cheat(Base):

  __tablename__ = 'cheats'

  id = Column(Integer, primary_key = True, autoincrement = True)
  cheat = Column(Text)
  name = Column(String(255), index = True)
  _html = Column('html', Text)
  _slug = Column('slug', String(255))

  @hybrid_property
  def html(self):
    return self._html

  @html.setter
  def set_html(self, md):
    from markdown import markdown
    self._html = markdown(md)

  @hybrid_property
  def slug(self):
    return self._slug

  @slug.setter
  def set_slug(self, name):
    self._slug = slugify(name)

  def __init__(self, name, cheat):
    self.name = name
    self.slug = name
    self.cheat = cheat
    self.html = cheat

  def __repr__(self):
    return "Cheat<%s>" % self.name

现在我可以从骗子那里得到所有东西:

Cheat.query.all()

和SQLAlchemy将生成类似于:

的SQL语句

SELECT name, slug, cheat, html FROM cheats

但我希望我的SQL语句是:

SELECT name, slug FROM cheats

所以我需要指定要检索的列,因为我不需要通过网络从数据库中提取大量文本。 我该怎么做?

2 个答案:

答案 0 :(得分:5)

将它们定义为deferred,然后只有在访问

时才会获取它们
from sqlalchemy.orm import deferred

class Cheat(Base):

  __tablename__ = 'cheats'

  id = Column(Integer, primary_key = True, autoincrement = True)
  cheat = deferred(Column(Text))
  name = Column(String(255), index = True)
  _html = Column('html', Text)
  _slug = deferred(Column('slug', String(255)))

答案 1 :(得分:4)

for name, slug in session.query(Cheat.name, Cheat.slug):
    print name, slug