filter/limit 姜戈 order_by

filter/limit django order_by

使用 django ORM,有没有办法限制或过滤 order_by 适用的范围?

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'
)

即使使用原始 SQL 也不可能仅对某些行应用 order by。所以最好的方法是,按 role_code 排序并分组。

你也可以得到 role_code "A01""B01" 的贡献者,订购它们,然后得到除 role_code 之外的其余贡献者,如果是 "A01""B01"。然后合并查询结果。

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