SQLAlchemy declarative. Specify columns to select

python, sqlalchemy

Solution

define them as deferred, then they will only be fetched when the're accessed

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)))

Problem

Declarative base: ``` Base = declarative_base() Base.query = Session.query_property() ``` The class: ``` 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 ``` Now I can get everything from the cheats: ``` Cheat.query.all() ``` and SQLAlchemy will generate SQL statement similar to: `SELECT name, slug, cheat, html FROM cheats` but I want my SQL statement to be: `SELECT name, slug FROM cheats` so I need to specify which columns I want to retrieve, because I don't really need to pull heavy texts from the database over the network. How do I do that?

Original source