Django基礎008 model多對多

2022-07-13 08:24:11 字數 1364 閱讀 6580

class

student(models.model):

name = models.charfield(verbose_name='

學生名字

',max_length=100)

class

meta:

db_table = '

student

'class

teacher(models.model):

name = models.charfield(verbose_name='

老師名字

',max_length=100)

student = models.manytomanyfield(student,verbose_name='學生'

)

class

meta:

db_table = '

teacher

'

#

多對多關係

teacher_obj = models.teacher.objects.get(id=2)

student_obj = models.student.objects.get(id=4)

#誰和誰去建立多對多關係

#建立多對多關係 方法1 add方法可以接受物件

teacher_obj.student.add(student_obj)

#建立多對多關係,方法2 add方法可以接收主鍵id

teacher_obj.student.add(3)#

#

刪除多對多關係

teacher_obj.student.clear()

#刪除指定資料

teacher_obj.student.remove(2) #

接收主鍵id

teacher_obj.student.remove(student_obj)

#接收物件

teacher_obj.student.set([1,2,3,4])#

新增,每次都會先刪除所有的繫結關係,再新增,比如乙個老師去別的班當班主任了

#

查詢多對多關係

#正向查詢

#獲取這個老師有哪些學生

students =teacher_obj.student.all()

print('

students

',students)

#反向查詢

#根據這個學生,查詢這個學生有幾個老師

teachers =student_obj.teacher_set.all()

print('

teachers

',teachers)

Python基礎 008 異常

異常 一些常見的異常 try f open data.txt f.read print zz print 5 0 except ioerror,e 捕獲io異常,變數e接收具體的錯誤資訊 print eexcept nameerror,e 捕獲名字異常 print eexcept exception...

為Django應用建立和啟用模型models

django的模型models,也就是資料庫的結構 每個生成的應用目錄中都有乙個 models.py 檔案,用來建立模型即資料庫結構 from django.db import models class question models.model question text models.charf...

Django根據資料庫表反向生成Model

用過django的人應該都熟悉下面兩條命令 python manage.py make migrations 此時資料庫中還不會生效 既然有根據model自動生成資料庫表的命令,那麼肯定就有根據資料庫表反向生成model的命令 python manage.py inspectdb 使用這條命令,會根...