filter/limit django order_by

无人久伴 提交于 2019-12-12 06:06:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!