2

声明基础:

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

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

4

2 回答 2

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)))
于 2012-04-30T17:44:22.410 回答
4
for name, slug in session.query(Cheat.name, Cheat.slug):
    print name, slug
于 2012-11-23T22:58:13.397 回答