Django 自定义排序 ORM

2023-08-21  本文已影响0人  alue

在 Django 中,打算对模型数据排序,但排序的方式是需要自定义的。有三种方式

  1. 将数据读取到内存之后,利用python自带的排序方式进行排序。

  2. 利用 Case-When 技术,让数据库来完成排序。

例如,模型如下

class ItemType(TextChoices):  
    A = '选择题', '选择题'  
    B = '填空题', '填空题'  
    C = '简单题', '简单题'  
 

class Item(models.Model):
    type = models.CharField(choices=options.ItemType.choices)

可以这样定义排序映射:

from django.db.models import  Case, Value, When

type_order = Case(  
    When(type=ItemType.A, then=Value(0)),  
    When(type=ItemType.B, then=Value(1)),  
    When(type=ItemType.C, then=Value(2)),  
)
Item.objects.alias(type_order=type_order).order_by(type_order)

这种方式,要比第一种方式更加高效。

  1. 定义 choices 时,存入数据的值是有顺序的,利用 choices 映射为显示值。这种方式很直观,效率更高,但缺点是需要多一次映射。
上一篇下一篇

猜你喜欢

热点阅读