Django merge QuerySet while keeping the order

Question:

i’m trying to join together 2 QuerySets. Right now, I’m using the | operator, but doing it this way won’t function as an "append".

My current code is:

df = RegForm((querysetA.all() | querysetB.all()).distinct())

I need the elements from querysetA to be before querysetB. Is it even possible to accomplish while keeping them just queries?

Asked By: Alberto Vona

||

Answers:

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()))
Answered By: Brian Destura