一對一:
一對一的關系極為一個數據僅對應一個數據,用下圖的結構圖可以幫助理解:
下面用代碼實現一下,首先要創建工程項目如下:
接著,我們定義模型:
來到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 pymysqlpymysql.install_as_MySQLdb()
下面可以遷移文件:
python manage.py makemigrationspython manage.py migrate
這樣我們就創建了兩個表:
來到views.py
文件中添加數據,代碼如下:
from django.shortcuts import renderfrom .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})
一對多
即一個對象對應著對個對象。
創建模型代碼:
from django.db import models# Create your models here.class People(models.Model): name = models.CharField(max_length=50) card_num = models.IntegerField(default=0)class Card(models.Model): number = models.CharField(max_length=20) person = models.ForeignKey(People,on_delete=models.CASCADE) source = models.CharField(max_length=50)
urls.py
路由設置:
from django.contrib import adminfrom django.urls import pathfrom myApp import viewsurlpatterns = [ path('admin/', admin.site.urls), path('add/',views.add), path('select/',views.select),]
新聞熱點
疑難解答