美文网首页
Django 自定义排序 ORM

Django 自定义排序 ORM

作者: alue | 来源:发表于2023-08-21 21:51 被阅读0次

    在 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 映射为显示值。这种方式很直观,效率更高,但缺点是需要多一次映射。

    相关文章

      网友评论

          本文标题:Django 自定义排序 ORM

          本文链接:https://www.haomeiwen.com/subject/vxsymdtx.html