flask_mongo_engine如何通过create_time desc分页命令?

时间:2018-09-26 14:31:13

标签: mongodb flask flask-mongoengine

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订购结果呢?

1 个答案:

答案 0 :(得分:1)

只需在paginate()之前添加order_by()

  

键可能以+或-前缀确定顺序

只是一个例子:

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)

希望这会有所帮助。