Django中資料庫的資料關係:一對一,一對多,多對多
阿新 • • 發佈:2018-12-09
一對一:
一對一的關係極為一個數據僅對應一個數據,用下圖的結構圖可以幫助理解:
下面用程式碼實現一下,首先要建立工程專案如下:
接著,我們定義模型:
來到models.py檔案,建立兩個模型:
from django.db import models # Create your models here. class One(models.Model): oname = models.CharField(max_length=20,null=True) oage = models.CharField(max_length=20,null=True) odate = models.DateField(null=True) class Two(models.Model): # 設定一對一關係,是通過將表中的欄位設定為主鍵完成的 # on_delete=models.CASCADE 當父表中的某一條資料刪除的時候 # 相關字表中的資料也會被刪除 tsub = models.OneToOneField(One,on_delete=models.CASCADE,primary_key=True) tfond = models.CharField(max_length=20,null=True) tdes = models.CharField(max_length=200,null=True)
來到myPro資料夾下新增以下兩句程式碼:
import pymysql pymysql.install_as_MySQLdb()
下面可以遷移檔案:
python manage.py makemigrations python manage.py migrate
這樣我們就建立了兩個表:
來到views.py檔案中新增資料,程式碼如下:
from django.shortcuts import render from .models import One,Two # Create your views here. def index(request): o1 = One.objects.create(oname='張三',oage=11,odate='2011-11-11') o2 = One.objects.create(oname='張三2',oage=12,odate='2012-12-12') t1 = Two.objects.create(tsub=o1,tfond='o1',tdes='我喜歡o1') t2 = Two.objects.create(tsub=o2,tfond='o2',tdes='我喜歡o2') return render(request,'index.html')
執行之後,將新增資料的程式碼註釋掉,否則後面每執行一次都會新增。
下面,我們通過查詢資料來甄別其中的關係。
def select(request): t1 = Two.objects.get(tsub__oname = '張三') return render(request,'index.html',{'t1':t1})