flask-sqlalchemy with_entities and relationships

偶尔善良 提交于 2020-02-03 18:53:49

问题


I want to select only a couple columns from my model to speed up the queries, but one of the columns I want to select is from a relationship.

Models:

class OpenChromatinRegion(db.Model):
    ...
    gene_id     = db.Column(db.Integer, db.ForeignKey("gene.id"), nullable=False, index=True)
    gene        = db.relationship("Gene", back_populates='open_chromatin_regions')

class Gene(db.Model):
    id          = db.Column(db.Integer, primary_key=True)
    ENSEMBLID   = db.Column(db.Integer, index=True, unique=True, nullable=False)
    ...

Query:

q = OpenChromatinRegion.query.with_entities(Gene.ENSEMBLID, ...)...

How do I properly select only a couple columns from OpenChromatinRegion using flask-sqlalchemy I previously tried .with_entities(OpenChromatinRegion.gene.ENSEMBLID) but that didn't work either. With this syntax, I don't get an error but the request times out.


回答1:


You need to do a join:

q = OpenChromatinRegion.query.join(OpenChromatinRegion.gene) \
                             .with_entities(Gene.ENSEMBLID)


来源:https://stackoverflow.com/questions/37797216/flask-sqlalchemy-with-entities-and-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!