Django:資料操作、查詢、過濾器、非過濾器方法
阿新 • • 發佈:2021-12-23
# -*- coding: utf-8 -*-
"""
資料操作、查詢、過濾器、非過濾器方法
"""
from random import randint
from django.shortcuts import render
from django.http import HttpResponse
from .models import User
# Create your views here.
def handle_data(request):
#增加記錄
# user = User(username='Jack1',password='111222')
# user.save()
# 批量建立
# firstname = "張李趙周王鄭"
# lastname = ["麗莉","德克","好","兒","童費","紅英","豆蔻"]
# users = []
# for name in range(10):
# user = firstname[randint(0,5)] + lastname[randint(0,6)] + str(randint(0,999))
# users.append(User(username=user,password=str(randint(111111,999999))))
# User.objects.bulk_create(users)
# # User.objects.bulk_create([User(username='test1',password='123456'),User(username='test2')])
# return HttpResponse("增加資料")
#修改記錄
user = User.objects.get(pk=1)
user.password = '333'
user.save()
return HttpResponse("資料修改")
# 刪除記錄
# try:
# user = User.objects.get(pk=1) #pk表示主鍵
# print(user,type(user))
# if user:
# user.delete()
# except Exception as e:
# print(e)
# return HttpResponse("資料刪除")
def search_data(request):
#過濾器1 : all 查詢所有
# users = User.objects.all()
# return render(request, "user_list.html", locals())
#過濾器2 :filter
# filter 相當於SQL中的 Where,可設定條件過濾結果
# users = User.objects.filter(uid__gt=150).filter(uid__lt=160) # __gt= : 大於 __lt= :小於
# return render(request, "user_list.html", locals())
#過濾器: order_by() 升序排序
# users = User.objects.filter(uid__gt=150).filter(uid__lt=160).order_by('username')
# return render(request, "user_list.html", locals())
#限制結果集
# users = User.objects.filter(uid__gt=150).filter(uid__lt=160).order_by('username')[:2] # 顯示前兩條資料
# return render(request, "user_list.html", locals())
#顯示指定欄位
# users = User.objects.values('username')
# return render(request, "user_list.html", locals())
#去重
users = User.objects.all().values('username').distinct()[:10]
return render(request, "user_list.html", locals())
# 非過濾方法
def process_query(request):
# # 1、get 只能返回一條資料,存在多條滿足篩選條件時,報錯
# user = User.objects.get(uid__gt= 173)
# print(user.username)
# return HttpResponse(f"get查詢結果是:{user.username}")
# # 2、first 返回一個模型物件
# user = User.objects.first()
# print(user.username)
# return HttpResponse(f"first查詢結果是:{user.username}")
# # 3、last 返回一個模型物件,查詢最後一條資料
# user = User.objects.last()
# print(user.username)
# return HttpResponse(f"last查詢結果是:{user.username}")
# # 4、count 顯示結果集的數量總數,必須是QuerySet才能呼叫
# num = User.objects.filter(uid__gt=100).count()
# print(num)
# return HttpResponse(f"count查詢結果是:{num}")
# 5、exists 判斷結果集是否為空
flag = User.objects.filter(uid__gt=100).exists()
print(flag)
return HttpResponse(f"exists查詢結果是:{flag}")