sqlalchemy:按变量属性查询

时间:2016-05-10 18:53:08

标签: sqlalchemy flask-sqlalchemy

这是我目前的代码:

def hypergeometric(query_genes, filename, input_format):

    if input_format == 'ENSEMBLID':
        OCRs = OpenChromatinRegion.query
                .filter(OpenChromatinRegion.filename == filename)
                .filter(OpenChromatinRegion.ENSEMBLID.in_(query_genes))
                .filter(OpenChromatinRegion.ENSEMBLID != 'NA')
                .all()

    elif input_format == 'gene_symbol':
        OCRs = OpenChromatinRegion.query
                .filter(OpenChromatinRegion.filename == filename)
                .filter(OpenChromatinRegion.gene_symbol.in_(query_genes))
                .filter(OpenChromatinRegion.gene_symbol != 'NA')
                .all()

由于显而易见的原因,这非常痛苦。有没有办法将input_format变量插入到查询中?

1 个答案:

答案 0 :(得分:2)

您可以使用 getattr 简单地提取所需属性,并在过滤器中使用它。

def hypergeometric(query_genes, filename, input_format):

     input_format_attribute = getattr(OpenChromatinRegion, input_format, None)     
     if input_format_attribute is not None:
        OCRs = OpenChromatinRegion.query
                .filter(OpenChromatinRegion.filename == filename)
                .filter(input_format_attribute.in_(query_genes))
                .filter(input_format_attribute != 'NA')
                .all()