博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django获取指定列的数据
阅读量:7072 次
发布时间:2019-06-28

本文共 1856 字,大约阅读时间需要 6 分钟。

django获取指定列的数据

model一般都是有多个属性的,但是很多时候我们又只需要查询特定的某一个,这个时候可以用到valuesvalues_list

[values()](https://docs.djangoproject.com/en/1.9/ref/models/querysets/#values)values()¶values(*fields)¶Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.
[values_list()](https://docs.djangoproject.com/en/1.9/ref/models/querysets/#values-list)values_list()¶values_list(*fields, flat=False)¶This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over. Each tuple contains the value from the respective field passed into the values_list() call — so the first item is the first field, etc.

看下面的代码:

利用values查询

from attendence.models import Employeefrom attendence.models import EmployeeIP#获取一个字段ipList = EmployeeIP.objects.values("IP").first()print(type(ipList))# 
print(ipList)# {'IP': '192.168.1.41'}#获取多个字段empList = Employee.objects.values("first_name", "last_name", "email")[0:2]print(type(empList))#
print(empList)# [# {'last_name': 'Wei', 'first_name': 'Vena', 'email': 'Vena@test.com'},# {'last_name': 'Wan', 'first_name': 'Mark', 'email': 'mwan@test.com'}# ]

利用values_list查询

ipList = EmployeeIP.objects.values_list("IP").first()print(type(ipList))# 
print(ipList)# ('192.168.1.111',)ipList = EmployeeIP.objects.values_list("IP")[0:2]print(type(ipList))#
print(ipList)# [('192.168.1.41',), ('192.168.1.44',)]print(type(ipList[0]))#
print(ipList[0])# 192.168.1.111

values和values_list的差别

从上面的代码中我们可以看到返回结果类型上细微的差别

  • vlaues -
    • 单条记录 - <class 'dict'>
    • 多条记录 - <class 'django.db.models.query.QuerySet'>
  • vlaues_list -
    • 单条记录 - <class 'tuple'>
    • 多条记录 - <class 'django.db.models.query.QuerySet'>

转载地址:http://znkml.baihongyu.com/

你可能感兴趣的文章
Docker如何管理数据
查看>>
Apache所有项目介绍
查看>>
Puppet apply命令参数介绍(五)
查看>>
linux系统命令su和su - 区别验证
查看>>
VMware vCloud Director Administration Guide
查看>>
pptpd *** 老是连接不上内网排错
查看>>
图文并茂超详细搭建redis缓存服务器(nginx+tomcat+redis+mysql实现session会话共享)
查看>>
云计算大数据(Hadoop)开发工程师项目实战视频教程(九部分)
查看>>
Verizon:2012年数据破坏调查报告
查看>>
《iPhone与iPad开发实战—iOS经典应用剖析》连载四
查看>>
手动完成输入校验
查看>>
直击Dell World 2014: 戴尔现在挺好的
查看>>
⑨③-不能浪费拥有的年轻资本
查看>>
自定义编译安装python简单笔记。
查看>>
书摘—极致产品
查看>>
5.10-17项目经理考试圆梦提分现场面授行动
查看>>
IT项目中存储设备的选型
查看>>
esxi报错There is no more space for virtual disk--逻辑卷缩减!
查看>>
NFS4中小企业存储实战
查看>>
Windows Server 2012 R2工作文件夹⑨:自动发现设置
查看>>