1. 程式人生 > >Django Models 常用操作及問題解決

Django Models 常用操作及問題解決

model.XXX.objects.get()不存在欄位解決方案

如何判斷從表單傳送過來的使用者名稱及密碼是否在資料庫中存在?

使用model.User.objects.get(username = username)的時候如果不存在查詢的值的話將會丟擲一個DoesNotExist的異常

可以使用try捕獲此異常進行判斷:

from django.core.exceptions import ObjectDoesNotExist
if request.method == 'POST':
		username = request.POST.get('username')
		passwd = mainHandle.getMd5(request.POST.get('passwd'))
		try:
			result = models.Admin.objects.get(username = username, passwd = passwd)
			pageObj = redirect('/admin/manage/')
			pageObj.set_signed_cookie('ck','log',salt = 'ck_liang')
			return pageObj
		except ObjectDoesNotExist:
			....


批量插入資料

	models.Class.objects.bulk_create([
			models.Class(cname = 'python'),
			models.Class(cname = 'java'),
			models.Class(cname = 'html5'),
			models.Class(cname = 'php'),
			models.Class(cname = 'django'),
			models.Class(cname = 'javascript'),
		])
teacherClass = []
for nameId in newCnameId:
	teacherClass.append(models.TeacherClass(tid_id = tid, cid_id = nameId))
models.TeacherClass.objects.bulk_create(teacherClass)


多表聯查

tList = A.objects.filter(name = 'admin').values_list('name','age', flat=True) # flat = True 返回一個列表,預設返回元組列表
B.objects.filter(name__in=tList).values_list('class')


通過外來鍵多表聯查

teacher和class表通過中間表關聯,並且為中間表設定外來鍵

class Teacher(models.Model):
	tid = models.AutoField(primary_key = True)
	tname = models.CharField(max_length = 5)

class Class(models.Model):
	cid = models.AutoField(primary_key = True)
	cname = models.CharField(max_length = 15)

class TeacherClass(models.Model):
	tcid = models.AutoField(primary_key = True)
	tid = models.ForeignKey(Teacher)
	cid = models.ForeignKey(Class)

通過中間表的外來鍵正向查詢

obj = models.TeacherClass.objects.filter(cid_id = 5) # 返回QuerySet物件列表
	for row in obj:
		print(row.tid.tname) # 通過當前表的外來鍵欄位正向查詢cid_id = 5的教師表中的教師姓名

反向查詢

obj = models.Teacher.objects.get(tid = 4) # 返回QuerySet物件列表
	for row in obj.teacherclass_set.all(): # 反向查詢的表名需全部小寫並加上_set
		print(row.cid_id)

values()取值時的正向跨表查詢 - (外來鍵名__欄位名)

obj = models.TeacherClass.objects.filter(tid_id = 5).values('cid_id','tid__tname') # 返回字典
print(obj)