简体   繁体   English

简单的SQLalchemy查询

[英]Simplying SQLalchemy queries

SQLalchemy query syntax is verbose: SQLalchemy查询语法很详细:

models.session.query(models.Person).filter(models.Person.first_name == 'David').all()

I've read several guides implying table objects have query method, but can't find it in the SQLalchemy docs, nor make it work in my code. 我已经阅读了几本暗示表对象具有查询方法的指南,但是无法在SQLalchemy文档中找到它,也无法使其在我的代码中起作用。 Is there any reason why I shouldn't use code like below? 有什么原因为什么我不应该使用下面的代码?

class QueryMethod:
    @classmethod
    def filter(cls, *args, **kwargs):
        return session.query(cls).filter(*args, **kwargs).all()


class Person(Base, QueryMethod):
    __tablename__ = 'people'

    id = Column(Integer, primary_key=True)
    first_name = Column(String(255))

New query syntax allowed by this inherritance: 此继承允许的新查询语法:

models.Person.filter(models.Person.first_name=='David')

My question: is there a way to remove the 'models.Person' bit inside the filter method call? 我的问题:有没有办法删除filter方法调用中的'models.Person'位?

I guess you are looking for filter_by . 我猜你在找filter_by The query would be something like 该查询将类似于

session.query(models.Person).filter_by(first_name="foo")

The filter classmethod that you have used harcodes the session . 您使用的filter类方法对session编码。 I would recommend that you pass the session explicitly to it so that the same query can be re-used over different sessions. 我建议您将会话明确传递给它,以便可以在不同的会话上重复使用同一查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM