SQLAlchemy查询不起作用

时间:2017-04-30 21:53:30

标签: python sqlalchemy

我有这个代码添加了一个'用户'使用指定的属性并稍后搜索它。但 get_row()使用 filter_by 总是返回None。

from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()


class User(Base):        
    __tablename__ = 'users'
    email = Column('email', String(40), primary_key=True)
    name = Column('name', String(40))
    password = Column('password', String)
    plan = Column('plan', String)
    apikey = Column('apikey', String)
    periodstart = Column('periodstart', Integer)
    confirmed = Column('confirmed', Integer)
    billed = Column('billed', Integer)


class SQLDb:
    def __init__(self, model):
        self.model = model
        uri = 'sqlite:///:memory:'
        self.engine = create_engine(uri, echo=True)
        Session = sessionmaker(bind=self.engine)
        self.session = Session()
        Base.metadata.create_all(self.engine)

    def __enter__(self):
        return self.session

    def modify_row(self, r):
        self.session.add(r)
        self.session.commit()

    def get_row(self, **kwargs):
        self.session.query(self.model).filter_by(**kwargs).first()

    def closedb(self):
        self.session.commit()

    def __exit__(self, a, b, c):
        self.closedb()


if __name__ == "__main__":
    user = User()
    user.email = 'test@example.com'
    user.name = 'john'
    user.password = 'test@123'
    user.plan = 'dummy'
    user.periodstart = 0
    user.confirmed = 0
    user.billed = 1
    sdb = SQLDb(User)
    sdb.modify_row(user)
    print(sdb.get_row(name='john'))

输出始终为:

我不明白这里出了什么问题。你能解释一下吗?

1 个答案:

答案 0 :(得分:2)

您只需要从函数返回结果。否则返回None

def get_row(self, **kwargs):
    return self.session.query(self.model).filter_by(**kwargs).first()