Django學習 9 ORM多對多操作

2022-08-04 08:09:15 字數 1403 閱讀 5984

建立多對多:

方式一:自定義關係表

class host(models.model):

nid = models.autofield(primary_key=true)

hostname = models.charfield(max_length=32,db_index=true)

ip = models.genericipaddressfield(protocol="ipv4",db_index=true)

port = models.integerfield()

b = models.foreignkey(to="business", to_field='id')

# 10

name = models.charfield(max_length=32)

# 2hobj = models.foreignkey(to='host',to_field='nid')

方式二:自動建立關係表

class host(models.model):

nid = models.autofield(primary_key=true)

hostname = models.charfield(max_length=32,db_index=true)

ip = models.genericipaddressfield(protocol="ipv4",db_index=true)

port = models.integerfield()

b = models.foreignkey(to="business", to_field='id')

# 10

name = models.charfield(max_length=32)

無法直接對第三張表進行操作

只能間接操作————————————————————

obj.name

obj.r.add(1)                                增

obj.r.add(2)

obj.r.add(2,3,4)

obj.r.add(*[1,2,3,4])

obj.r.remove(1)                           刪

obj.r.remove(2,4)

obj.r.remove(*[1,2,3])

obj.r.set([3,5,7])                           改                set將原來資料庫中的關係先全部刪除,在新增1-3,1-5,1-7

——————————————————————————

# 所有相關的主機物件「列表」 queryset

obj.r.all()            obj.filter()  obj.first()

前端取{%endfor%}   

Django 40 ORM多對多新增

前提 初始表資料 book表和author表為多對多關係,一本圖書可能有多個作者,乙個作者可能有多本書 新增add 可以為數字 即id 物件 物件列表 book表 author表 book authors表 關係表 from django.shortcuts import render 匯入顯示頁面...

Django 44 ORM多對多刪除

前提 初始表資料 remove 刪除,可以為數字 即id 物件 物件列表 delete篩選後刪除 clear清空 book表 author表 book authors表 關係表 from django.shortcuts import render 匯入顯示頁面的模組 from django.htt...

Django中ORM多對多三種建立方式

一 多對多三種建立方式 1.全自動 利用orm自動幫我們建立第三張關係表class book models.model name models.charfield max length 32 authors models.manytomanyfield to author class author ...