我知道这个问题有点老了,但我遇到了这个问题并且没有找到非常高效的解决方案,所以我希望它可以帮助某人。
我想出了两个很好的解决方案。
第一个更优雅,但性能稍差。第二个明显更快,尤其是对于较大的查询集,但它使用原始 SQL 结合。
它们都可以找到上一个和下一个 ids,但当然可以进行调整以检索实际的对象实例。
第一种解决方案:
object_ids = list(filtered_objects.values_list('id', flat=True))
current_pos = object_ids.index(my_object.id)
if current_pos < len(object_ids) - 1:
next_id = object_ids[current_pos + 1]
if current_pos > 0:
previous_id = object_ids[current_pos - 1]
第二个解决方案:
window = {'order_by': ordering_fields}
with_neighbor_objects = filtered_objects.annotate(
next_id=Window(
Lead('id'),
**window
),
previous_id=Window(
Lag('id'),
**window
),
)
sql, params = with_neighbor_objects.query.sql_with_params()
# wrap the windowed query with another query using raw SQL, as
# simply using .filter() will destroy the window, as the query itself will change.
current_object_with_neighbors = next(r for r in filtered_objects.raw(f"""
SELECT id, previous_id, next_id FROM ({sql}) filtered_objects_table
WHERE id=%s
""", [*params, object_id]))
next_id = current_object_with_neighbors.next_id:
previous_id = current_object_with_neighbors.previous_id: