我用python编写了一段代码,使用sqlalchemy从MySQL获取数据。当页面为1(开始为0,结束为10)时,一切正常,但是当页面为2(开始为10,结束为20)时,db_salon和db_user_paymant为空。
我尝试使用join和joinedload,但仍然不起作用。
def get_user_bookings(db: Session, user_id: int, page: int):
start = (page - 1) * 10
end = (page * 10)
db_user_bookings = db.query(DbBasketMain).options(
subqueryload("db_basket_services"), subqueryload("db_salon"),
subqueryload("db_user_payment")).filter(
DbBasketMain.user_id == user_id, DbBasketMain.salon_id != None).slice(
start, end).all()
for each_booking in db_user_bookings:
each_booking.salon_name = each_booking.db_salon.name
for each_service in each_booking.db_basket_services:
if (each_service.barber_id):
db_barber = get_barber_by_id(
db=db, barber_id=each_service.barber_id)
each_service.barber_name = db_barber.name + " " + db_barber.family
each_service.barber_image = get_barber_profile_image(
db=db, barber_id=each_service.barber_id)
return db_user_bookings
发布于 2020-09-20 06:41:00
使用slice时,必须使用order_by
。
改用order_by(DbBasketMain.id).slice(start, end)
解决了这个问题。
https://stackoverflow.com/questions/63926627
复制