django獲取指定列的數據


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 Employee
from attendence.models import EmployeeIP

#獲取一個字段
ipList = EmployeeIP.objects.values("IP").first()
print(type(ipList))
# <class 'dict'>
print(ipList)
# {'IP': '192.168.1.41'}

#獲取多個字段
empList = Employee.objects.values("first_name", "last_name", "email")[0:2]
print(type(empList))
# <class 'django.db.models.query.QuerySet'>
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))
# <class 'tuple'>
print(ipList)
# ('192.168.1.111',)

ipList = EmployeeIP.objects.values_list("IP")[0:2]
print(type(ipList))
# <class 'django.db.models.query.QuerySet'>
print(ipList)
# [('192.168.1.41',), ('192.168.1.44',)]
print(type(ipList[0]))
# <class 'tuple' >
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'>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM