简体   繁体   中英

FastAPI Sqlalchemy get lastest result

I have setup my first Python FastAPI but getting stuck. I have a function that query some results. The following function query the first entry in the database on a specific date. Now I want the last entry on a date or all results sort by highest id but how do i do this?

def get_workday(db: Session, workday_date: date):
    return db.query(DBWorkday).where(DBWorkday.date == workday_date).first()

full code:

from datetime import date
from fastapi import FastAPI, Depends
from pydantic import BaseModel
from typing import Optional, List
from sqlalchemy import Date, create_engine
from sqlalchemy.orm import declarative_base, sessionmaker, Session
from sqlalchemy import Column, String, Integer

app = FastAPI()

# SqlAlchemy Setup
SQLALCHEMY_DATABASE_URL = 'sqlite:///../db/database.db'
engine = create_engine(SQLALCHEMY_DATABASE_URL, echo=True, future=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()


# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# A SQLAlchemny ORM


class DBWorkday(Base):
    __tablename__ = 'workdays'

    id = Column(Integer, primary_key=True, index=True)
    date = Column(Date)
    start_time = Column(String(4))
    end_time = Column(String(4))
    type = Column(String, nullable=True)
    location = Column(String, nullable=True)


Base.metadata.create_all(bind=engine)

# Workday Pydantic model


class Workday(BaseModel):
    date: date
    start_time: str
    end_time: str
    type: Optional[str] = None
    location: Optional[str] = None

    class Config:
        orm_mode = True

# Methods for interacting with the database


def get_workday(db: Session, workday_date: date):
    return db.query(DBWorkday).where(DBWorkday.date == workday_date).first()


@app.get('/workday/{date}')
def get_workday_view(date: date, db: Session = Depends(get_db)):
    return get_workday(db, date)
return db.query(DBWorkday).where(DBWorkday.date == workday_date).order_by(DBWorkday.id.desc()).first()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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