ordery_by 过滤器在 django 中无法正常工作
ordery_by filter is not working properly in django
data = models.Booking.objects.filter(center__isnull=False,org_type='homedx').order_by('-created_at')
return data.order_by( Case(
When ( booking_status="resampling", then=Value(0) ),
When ( booking_status="sample not received", then=Value(1) ),
default = Value(1)
)
)
created_at 是预订模型中的 DateTimeField。在这里,我按选择字段排序,为此我使用了 django.db.models 中的 Case、When 和 Value 方法。但是当我使用它时,它忽略了 order_by created_at。我的意思是当满足这两个条件时。我想按最新日期的顺序获取数据。为什么它不起作用?谢谢!!
因为您现在有 两个 .order_by(…)
子句,并且在 documentation of .order_by(…)
:
中指定
Each order_by()
call will clear any previous ordering. For example, this query will be ordered by pub_date and not headline:
Entry.objects.order_by('headline').order_by('pub_date')
您可以在 .order_by(…)
子句中添加两个字段,因此:
return models.Booking.objects.filter(center__isnull=False,org_type='homedx').order_by(
<strong>'-created_at'</strong>, # 🖘 first field
Case( # 🖘 second field
When(booking_status='resampling', then=Value(0)),
default=Value(1)
).asc()
)
因此,这将首先对 created_at
字段进行排序,如果 并列 则按 booking_status
排序。如果您希望预订状态优先,可以将两者互换。
data = models.Booking.objects.filter(center__isnull=False,org_type='homedx').order_by('-created_at')
return data.order_by( Case(
When ( booking_status="resampling", then=Value(0) ),
When ( booking_status="sample not received", then=Value(1) ),
default = Value(1)
)
)
created_at 是预订模型中的 DateTimeField。在这里,我按选择字段排序,为此我使用了 django.db.models 中的 Case、When 和 Value 方法。但是当我使用它时,它忽略了 order_by created_at。我的意思是当满足这两个条件时。我想按最新日期的顺序获取数据。为什么它不起作用?谢谢!!
因为您现在有 两个 .order_by(…)
子句,并且在 documentation of .order_by(…)
:
Each
order_by()
call will clear any previous ordering. For example, this query will be ordered by pub_date and not headline:Entry.objects.order_by('headline').order_by('pub_date')
您可以在 .order_by(…)
子句中添加两个字段,因此:
return models.Booking.objects.filter(center__isnull=False,org_type='homedx').order_by(
<strong>'-created_at'</strong>, # 🖘 first field
Case( # 🖘 second field
When(booking_status='resampling', then=Value(0)),
default=Value(1)
).asc()
)
因此,这将首先对 created_at
字段进行排序,如果 并列 则按 booking_status
排序。如果您希望预订状态优先,可以将两者互换。