筛选/限制Django order_by [英] filter/limit django order_by

查看:103
本文介绍了筛选/限制Django order_by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

即使使用原始SQL,也无法仅对某些行应用订单。因此,最好的方法是将alls排序并按role_code分组。

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.

您还可以使用 role_code A01 或 B01 ,对其进行订购,然后获取其余贡献者(如果 role_code ) > A01 或 B01 。然后合并查询结果。

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

这篇关于筛选/限制Django order_by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆