I know this question is a little bit old but I came across this and didn't find very performant solutions, so I hope it may help someone.
There are 2 pretty good solutions I came up with.
The 1st is more elegant although slightly worse-performing. The 2nd is significantly faster, especially for larger QuerySets, but it combines using Raw SQL.
They both find previous & next ids, but can, of course, be tweaked to retrieve actual object instances.
1st solution:
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]
2nd solution:
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: