flask_mongo_engine 如何按 create_time desc 对顺序进行分页?
flask_mongo_engine how to paginate order by create_time desc?
class Session(db.DynamicDocument):
title = db.StringField(required=False)
created = db.FloatField(required=True)
source = db.StringField()
@app.route('/page/<int:page>')
def sessions(page):
return jsonify(Session.objects.paginate(page=page, per_page=5).items)
返回的是字典列表,默认为ASC,第一页包含最早的文档。
那么如何获取desc订单结果呢?
只需在 paginate() 之前添加 order_by()。
keys may be prefixed with + or - to determine the ordering direction
举个例子:
class Session(db.DynamicDocument):
create_time = db.DateTimeField(required=True)
# clean before test
for i in Session.objects.all():
i.delete()
for i in range(20):
create_time = datetime.now()
create_time = create_time.replace(year=2000 + i)
ses = Session(create_time=create_time)
ses.save()
print('2000 -> 2009')
items = Session.objects.order_by('create_time').paginate(page=1, per_page=10).items
for i in items:
print(i.create_time)
print('2019 -> 2010')
items = Session.objects.order_by('-create_time').paginate(page=1, per_page=10).items
for i in items:
print(i.create_time)
希望对您有所帮助。
class Session(db.DynamicDocument):
title = db.StringField(required=False)
created = db.FloatField(required=True)
source = db.StringField()
@app.route('/page/<int:page>')
def sessions(page):
return jsonify(Session.objects.paginate(page=page, per_page=5).items)
返回的是字典列表,默认为ASC,第一页包含最早的文档。
那么如何获取desc订单结果呢?
只需在 paginate() 之前添加 order_by()。
keys may be prefixed with + or - to determine the ordering direction
举个例子:
class Session(db.DynamicDocument):
create_time = db.DateTimeField(required=True)
# clean before test
for i in Session.objects.all():
i.delete()
for i in range(20):
create_time = datetime.now()
create_time = create_time.replace(year=2000 + i)
ses = Session(create_time=create_time)
ses.save()
print('2000 -> 2009')
items = Session.objects.order_by('create_time').paginate(page=1, per_page=10).items
for i in items:
print(i.create_time)
print('2019 -> 2010')
items = Session.objects.order_by('-create_time').paginate(page=1, per_page=10).items
for i in items:
print(i.create_time)
希望对您有所帮助。