问题
Using the django ORM, Is there a way to limit or filter the scope of what order_by applies to?
Product.objects.filter(
product_type__name=choices.PRODUCT_BOOK
).order_by(
# need to order these last names by those
# who have a role code of "A01", then "B01"
'contributor__writer__last_name'
)
回答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
来源:https://stackoverflow.com/questions/28773764/filter-limit-django-order-by