本文實例講述了django框架使用views.py函數對表進行增刪改查內容操作。分享給大家供大家參考,具體如下:
models之對于表的創建有以下幾種:
一對一:ForeignKey("Author",unique=True), OneToOneField("Author")
一對多:ForeignKey(to="Publish",to_field="id",on_delete.CASCADE)
多對多:ManyToManyField(to="Author")
首先我們來創建幾張表
from django.db import models# Create your models here.class AuthorDetail(models.Model): gf=models.CharField(max_length=32) tel=models.CharField(max_length=32)class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField() # 與AuthorDetail建立一對一的關系 # ad=models.ForeignKey(to="AuthorDetail",to_field="id",on_delete=models.CASCADE,unique=True) ad=models.OneToOneField(to="AuthorDetail",to_field="id",on_delete=models.CASCADE,)class Publish(models.Model): name=models.CharField(max_length=32) email=models.CharField(max_length=32) addr=models.CharField(max_length=32)class Book(models.Model): title=models.CharField(max_length=32,unique=True) price=models.DecimalField(max_digits=8,decimal_places=2,null=True) pub_date=models.DateField() # 與Publish建立一對多的關系,外鍵字段建立在多的一方 publish=models.ForeignKey(to="Publish",to_field="id",on_delete=models.CASCADE) # 與Author表建立多對多的關系,ManyToManyField可以建在兩個模型中的任意一個,自動創建關系表book_authors authors=models.ManyToManyField(to="Author")
說明:
OneToOneField 表示創建一對一關系。
to 表示需要和哪張表創建關系
to_field 表示關聯字段
on_delete=models.CASCADE
表示級聯刪除。假設a表刪除了一條記錄,b表也還會刪除對應的記錄。ad表示關聯字段,但是ORM創建表的時候,會自動添加_id后綴。那么關聯字段為ad_id
注意:創建一對一關系,會將關聯字添加唯一屬性。比如:ad_id
ForeignKey 表示建立外鍵
on_delete=models.CASCADE
表示級聯刪除。使用ForeignKey必須要加on_delete。否則報錯。這是2.x規定的ManyToManyField 表示建立多對多的關系。它只需要一個to參數,表示和哪張表創建多對多關系!
這里是在book模型下定義了多對多關系,它會自動創建一張額外的關系表。表的名字就是當前模型的名字(book)+關系的屬性名(等式左邊的屬性名authors)。
也就是會創建表book_authors,它只有3個字段,分別是:本身表的id,boo表主鍵id,authors表主鍵id。
下面在視圖 views.py里面使用
from django.shortcuts import render,HttpResponsefrom app01.models import AuthorDetail,Author,Publish,Book# Create your views here.def add(request): # 注意:因為author的ad屬性是關聯authordetail表,必須添加authordetail表,才能添加author表。 # hong_gf=AuthorDetail.objects.create(gf='小唐',tel=1314) # hong=Author.objects.create(name='hong',age='25',ad=hong_gf) # print(hong) # # publish_id就是Book類的publish屬性。它的字段為publish_id # book = Book.objects.create(title='西游記', price=100, pub_date="1743-4-12", publish_id=2) # print(book.title) # 打印title # return HttpResponse('添加成功') # xigua = Publish.objects.filter(name="西瓜出版社").first() #model對象 # book = Book.objects.create(title='三國演義',price=300,pub_date="1643-4-12",publish=xigua) # return HttpResponse('添加成功')
新聞熱點
疑難解答