模型管理器/QuerySet 常見的方法
get([**kwargs])
方法
- 用途:獲取滿足條件的唯一對象。
- 參數:關鍵字參數,指定查詢條件。
- 返回值:模型對象。
- 異常:如果找到多個對象或未找到對象,將分別拋出
MultipleObjectsReturned
和DoesNotExist
異常。
示例:
try:student = Student.objects.get(pk=1)
except Student.DoesNotExist:print("No student found with pk=1")
except Student.MultipleObjectsReturned:print("Multiple students found with the same pk")
first()
方法
- 用途:返回查詢集中的第一個對象(如果存在)。
- 參數:無。
- 返回值:模型對象或
None
(如果查詢集為空)。
示例:
student = Student.objects.filter(age__gt=18).first()
if student:print(student.name)
else:print("No student older than 18 found")
last()
方法
- 用途:返回查詢集中的最后一個對象(如果存在)。
- 參數:無。
- 返回值:模型對象或
None
(如果查詢集為空)。
示例:
student = Student.objects.filter(graduated=False).last()
if student:print(student.name)
else:print("No current student found")
count()
方法
- 用途:返回查詢集中的對象數量。
- 參數:無。
- 返回值:整數。
示例:
num_students = Student.objects.count()
print(f"Total number of students: {num_students}")
filter(**kwargs)
方法
- 用途:根據給定的條件篩選對象。
- 參數:關鍵字參數,指定查詢條件。
- 返回值:
QuerySet
對象。
示例(已在問題描述中給出)。
exclude(**kwargs)
方法
- 用途:排除滿足給定條件的對象。
- 參數:關鍵字參數,指定排除條件。
- 返回值:
QuerySet
對象。
示例(已在問題描述中給出)。
all()
方法
- 用途:獲取查詢集中的所有對象。
- 參數:無。
- 返回值:
QuerySet
對象。
示例(已在問題描述中給出)。
values(*fields)
方法
- 用途:返回包含指定字段值的字典的
QuerySet
。 - 參數:字段名稱的列表或可變參數。
- 返回值:包含字典的
QuerySet
對象。
示例(已在問題描述中給出),但注意,values()
返回的 QuerySet
中的每個元素都是字典,而不是模型實例。
order_by(*fields)
方法
- 用途:對查詢結果進行排序。
- 參數:字段名稱的列表或可變參數。字段前加
-
表示降序排序。 - 返回值:排序后的
QuerySet
對象。
示例(已在問題描述中給出)。
distinct()
方法
- 用途:對查詢結果進行去重。
- 參數:無。
- 返回值:去重后的
QuerySet
對象。 - 注意:通常與
values()
方法一起使用以指定去重的字段。
示例(稍作修改):
# 假設有多個學生可能有相同的姓名和性別,但其他字段不同
unique_names_sexes = Student.objects.values("name", "sex").distinct()
for item in unique_names_sexes:print(item)
額外方法
exists()
方法
- 用途:檢查查詢集是否包含至少一個對象。
- 參數:無。
- 返回值:布爾值。
示例:
if Student.objects.filter(enrolled=True).exists():print("There are enrolled students")
values_list(*fields, flat=False)
方法
- 用途:返回包含指定字段值的元組的
QuerySet
。 - 參數:字段名稱的列表或可變參數;
flat=True
時,如果查詢集只包含一個字段,則返回該字段值的列表而不是元組的列表。 - 返回值:包含元組的
QuerySet
對象或字段值的列表(如果flat=True
)。
示例:
# 獲取所有學生的ID和姓名,作為元組列表
students_info = Student.objects.values_list("id", "name")
for student_info in students_info:print(student_info)# 僅獲取所有學生的姓名,作為列表
students_names = Student.objects.values_list("name", flat=True)
for name in students_names:print(name)
這些方法提供了強大的查詢和數據處理能力,使得Django的ORM成為處理數據庫操作的有力工具。