SQLAlchemy - 如何选择cerain行?

时间:2016-04-04 19:19:09

标签: python select sqlalchemy

如何在SELECT中模拟SQLAlchemy?我想创建一个函数,它接受一些参数并返回一行包含这些值,但我不能SELECT

我找到的唯一方法是在下方,但我无法在metadata模块中找到SQLAlchemy

编辑:我发现BoundMetaData已被弃用,因此MetaData是合适的,但它表示Select has no len

# -*- coding: utf-8 -*-
import sqlalchemy
from sqlalchemy import Column, Table
from sqlalchemy import UniqueConstraint
from sqlalchemy import create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///db.db', echo=False)
Base = declarative_base()

s = sqlalchemy.orm.Session(engine)


class Flight(Base):
    __tablename__ = 'flights'

    id = Column(sqlalchemy.Integer, primary_key=True)
    destination_from = Column(sqlalchemy.String)
    destination_to = Column(sqlalchemy.String)
    creation_date = Column(sqlalchemy.Date)
    start_date = Column(sqlalchemy.Date)
    return_date = Column(sqlalchemy.Date)
    price = Column(sqlalchemy.Float)
    filename = Column(sqlalchemy.String)
    bought_days_before = Column(sqlalchemy.Integer)

    __table_args__ = (
        UniqueConstraint('creation_date', 'destination_from', 'destination_to', 'start_date', 'return_date', 'price'),
    )


Base.metadata.create_all(engine)


def insert_into_flights(**kwargs):
    s.add(Flight(**kwargs))
    try:
        s.commit()
    except IntegrityError as e:
        s.rollback()


def get_prices(date_from, days, bought_days_before, destination, min=True, avg=False):
    flights = Table('flights', metadata ,autoload=True
                )
    print len(flights.select())

1 个答案:

答案 0 :(得分:2)

s.query(Flight).filter(Flight.id==34).all()

这是选择ID为34的航班的示例。 见SQLAlchemy docs