filter/limit django order_by

2019-09-09 22:33发布

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条回答
一纸荒年 Trace。
2楼-- · 2019-09-09 22:53

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
查看更多
登录 后发表回答