[Django]-Django merge QuerySet while keeping the order

5👍

This can be solved by using annotate to add a custom field for ordering on the querysets, and use that in a union like this:

from django.db.models import Value

a = querysetA.annotate(custom_order=Value(1))
b = querysetB.annotate(custom_order=Value(2))
a.union(b).order_by('custom_order')

Prior to , you need to specify the output_field for Value:

from django.db.models import IntegerField

a = querysetA.annotate(custom_order=Value(1, IntegerField()))
b = querysetB.annotate(custom_order=Value(2, IntegerField()))

Leave a comment