Django slice a single field in a queryset

后端 未结 1 689
陌清茗
陌清茗 2020-12-11 08:34

I am trying to grab the first five characters from a char field but for only one field in a queryset but I keep getting various errors. Is there an effective way to do this

相关标签:
1条回答
  • 2020-12-11 09:01

    You can annotate the queryset with first 5 letters of field2 using Substr function:

    from django.db.models.functions import Substr 
    queryset = Model.objects.all() 
    queryset = queryset.annotate(field2_5=Substr('field2', 1, 5)) 
    

    And, then use the annotated field field2_5 in values:

    values = queryset.values('field1', 'field2_5', 'field3')
    
    0 讨论(0)
提交回复
热议问题