2012-04-30 70 views
2

聲明基地: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

,所以我需要指定我想要檢索的列,因爲我不真的需要在從數據庫中提取文本重網絡。 我該怎麼做?

回答

4

它們定義爲deferred,那麼他們將只取時the're訪問

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))) 
4
for name, slug in session.query(Cheat.name, Cheat.slug): 
    print name, slug