【发布时间】:2020-08-19 00:19:03
【问题描述】:
当我尝试根据创建日期返回文档时,当我知道数据库中有符合条件的文档时,我会得到一个空列表。我使用邮递员发送请求,该请求将是用户输入的字符串,例如。 "Tue Apr 28 2020"。然后,此字符串输入将被转换为日期时间对象,如下所示:
def get(self):
try:
body = request.get_json()
search_field = datetime.datetime.strptime(body, '%a %b %d %Y') #format string to datetime object
next_day = search_field
next_day += relativedelta(days=1) #Set the end of the range to the next day
search_field = search_field.replace(tzinfo=datetime.timezone.utc).isoformat()
next_day = next_day.replace(tzinfo=datetime.timezone.utc).isoformat()
print(search_field) #Verify the fields are correct : 2020-04-28T00:00:00+00:00
print(next_day) #2020-04-29T00:00:00+00:00
date_search = Reports.objects.filter(__raw__={'creation_timestamp' : {'$gte' : search_field, '$lte' : next_day}}).to_json() #This is where the documents should be filtered for return
print(date_search)
return Response(date_search, mimetype="application/json", status=200) #The document/s should be returned here as a JSON array.
except Exception as e:
print(e)
return make_response(jsonify(message='Something went wrong :('), 401)
这是部分数据库模型:
class Reports(db.Document):
creation_timestamp = db.DateTimeField(default=datetime.utcnow, required=True)
文档创建时存储在数据库中,时间存储为isoformat()。用户只能使用日期选择器以上述格式输入搜索字段,因此我格式化日期以适应 Mongodb 可以理解的格式。
使用上面的代码,我得到一个空列表和 200 状态代码。检查数据库显示我有符合标准的文件,任何人都可以帮助找出问题所在吗?谢谢。
【问题讨论】:
-
打印(date_search)时是否得到输出?
标签: python mongodb flask pymongo mongoengine