我试图过滤以下用户:
问题是有时候在过去的5秒内没有用户。在这种情况下,我想从查询中取出它,因为它会使我的列表索引超出范围并抛出错误。
所以我首先定义了我的异常子句,然后希望如果try:block没有抛出indexError就会重写它。这没有发生,它仍然会抛出错误。如何避免错误?
recent_range = datetime.now() - timedelta(seconds=5)
all_users = User.objects.filter(gender=user_preference).\
filter(preference=user_gender).order_by('?').exclude(email=request.user.email)
try:
all_users = User.objects.filter(gender=user_preference).\
filter(preference=user_gender).filter(online=recent_range).\
order_by('?').exclude(email=request.user.email)
except IndexError:
pass
other_user = all_users[0]
答案 0 :(得分:0)
all_users = User.objects.filter(gender=user_preference).\
filter(preference=user_gender).order_by('?').exclude(email=request.user.email)
other_user = all_users[0]
try:
all_users = User.objects.filter(gender=user_preference).\
filter(preference=user_gender).filter(online=recent_range).\
order_by('?').exclude(email=request.user.email)
other_user = all_users[0]
except:
pass