Django在查询集中切片单个字段 [英] Django slice a single field in a queryset

查看:91
本文介绍了Django在查询集中切片单个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个char字段中获取前五个字符,但对于查询集中的一个字段,却一直出现各种错误。在视图中是否有有效的方法?

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 in the view?

我正在尝试的代码:

var = Model.objects.values('field1', 'field2'[:5], 'field3')


推荐答案

您可以使用 field2 的前5个字母注释查询集。 ://docs.djangoproject.com/en/1.10/ref/models/database-functions/#substr rel = noreferrer> Substr 函数:

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)) 

,然后在值中使用带注释的字段 field2_5

And, then use the annotated field field2_5 in values:

values = queryset.values('field1', 'field2_5', 'field3')

这篇关于Django在查询集中切片单个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆