I recently found that .sort() in my code has been interrupted by my other code. I want to list the set of documents posted in 30days and sort it in most liked order. Previous work to this was to find all documents in all time so, my code had sorting with likes already and then I added period.
The problem is that my list is being sorted with likes within dates. for example, the most liked document is listed under less liked document that has some likes but posted in more recent date.
Here is my code
@app.route('/api/list/monthly_hot', methods=['GET'])
def show_monthly_hot():
fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
all = list(db.collection.find({}, {'_id': False}).sort('like', -1))
hot_posts = []
for i in range(0, 30):
target = today - timedelta(days=i)
period = target.strftime(fmt)
for x in all:
if x['date'] == period:
y = x
hot_posts.append(y)
return jsonify({'hot_posts': hot_posts})
So I tried to put .sort() in different variables
@app.route('/api/list/monthly_hot', methods=['GET'])
def show_monthly_hot():
fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
all = list(db.collection.find({}, {'_id': False}).sort('like', -1))
hot_posts = [].sort('like', -1)
for i in range(0, 30):
target = today - timedelta(days=i)
period = target.strftime(fmt)
for x in all:
if x['date'] == period:
y = x.sort('like', -1)
hot_posts.append(y).sort('like', -1)
return jsonify({'hot_posts': hot_posts}).sort('like', -1)
= failed(tried one at a time, not all lines like the above)
I tried How do I sort a list of dictionaries by a value of the dictionary?
@app.route('/api/list/monthly_hot', methods=['GET'])
def show_monthly_hot():
fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
all = list(db.collection.find({}, {'_id': False}).sort('like', -1))
hot_posts = []
for i in range(0, 30):
target = today - timedelta(days=i)
period = target.strftime(fmt)
for x in all:
if x['date'] == period:
y = sorted(x, key=itemgetter('like'), reverse=True)
hot_posts.append(y)
return jsonify({'hot_posts': hot_posts})
= failed