How to chain Django querysets preserving individual order

django, django-queryset, python

Solution

This solution prevents duplicates:

q1 = Q(...)
q2 = Q(...)
q3 = Q(...)
qs = (
    Model.objects
    .filter(q1 | q2 | q3)
    .annotate(
        search_type_ordering=Case(
            When(q1, then=Value(2)),
            When(q2, then=Value(1)),
            When(q3, then=Value(0)),
            default=Value(-1),
            output_field=IntegerField(),
        )
    )
    .order_by('-search_type_ordering', ...)
)

Problem

I'd like to append or chain several Querysets in Django, preserving the order of each one (not the result). I'm using a third-party library to paginate the result, and it only accepts lists or querysets. I've tried these options: Queryset join: Doesn't preserve ordering in individual querysets, so I can't use this. ``` result = queryset_1 | queryset_2 ``` Using itertools: Calling `list()` on the chain object actually evaluates the querysets and this could cause a lot of overhead. Doesn't it? ``` result = list(itertools.chain(queryset_1, queryset_2)) ``` How do you think I should go?

Original source

Related problems