1
Even using raw SQL is not possible to apply an order by just to some rows. So the best way, order alls and group by role_code.
Also you can get contributors with role_code
"A01"
or "B01"
, order them, then get the rest contributors excluding their role_code
if is "A01"
or "B01"
. Then merge query results.
order_products = Product.objects.filter(
product_type__name=choices.PRODUCT_BOOK
).filter(contributor__role_code__in=['A01','B01'])
.order_by(
# need to order these last names by those
# who have a role code of "A01", then "B01"
'contributor__writer__last_name'
)
non_order_products = Product.objects.filter(
product_type__name=choices.PRODUCT_BOOK
).exclude(contributor__role_code__in=['A01','B01'])
final_result = order_products | non_order_products
Source:stackexchange.com