如何在基于字段值的条件下在单个 Django 查询中使用多个 order_by
How to use multiple order_by in single Django query with conditions based on field values
如何使单个查询中的 order_by 字段依赖于字段值?
例如,
- if field status==10 然后升序排序
- if field status==20 then sort descending
您可以像这样在 order_by
中使用 conditions:
from django.db.models import Case, When
Model.objects.order_by(
Case(When(status='10', then='some_field')).asc(),
Case(When(status='20', then='some_field')).desc())
如何使单个查询中的 order_by 字段依赖于字段值?
例如,
- if field status==10 然后升序排序
- if field status==20 then sort descending
您可以像这样在 order_by
中使用 conditions:
from django.db.models import Case, When
Model.objects.order_by(
Case(When(status='10', then='some_field')).asc(),
Case(When(status='20', then='some_field')).desc())