Django基礎之Model操作,django基礎model
一、資料庫操作1、建立model表
基本結構:
1 #coding:Utf82 from django.db import models3 4 class userinfo(models.Model):5 #如果沒有models.AutoField,預設會建立一個id的自增列6 name = models.CharField(max_length=30)7 email = models.EmailField()8 memo = models.TextField()
欄位解釋:
1 1、models.AutoField 自增列= int(11) 2 如果沒有的話,預設會產生一個名稱為 id 的列,如果要顯示的自訂一個自增列,必須將給列設定為主鍵 primary_key=True。 3 2、models.CharField 字串欄位 4 必須 max_length 參數 5 3、models.BooleanField 布爾類型=tinyint(1) 6 不可為空,Blank=True 7 4、models.ComaSeparatedIntegerField 用逗號分割的數字=varchar 8 繼承CharField,所以必須 max_lenght 參數 9 5、models.DateField 日期類型 date10 對於參數,auto_now =True則每次更新都會更新這個時間;auto_now_add 則只是第一次建立添加,之後的更新不再改變。11 6、models.DateTimeField 日期類型 datetime12 同DateField的參數13 7、models.Decimal 十進位小數類型= decimal14 必須指定整數位max_digits和小數位decimal_places15 8、models.EmailField 字串類型(Regex郵箱)=varchar16 對字串進行Regex17 9、models.FloatField 浮點類型= double18 10、models.IntegerField 整形19 11、models.BigIntegerField 長整形20 integer_field_ranges ={21 'SmallIntegerField':(-32768,32767),22 'IntegerField':(-2147483648,2147483647),23 'BigIntegerField':(-9223372036854775808,9223372036854775807),24 'PositiveSmallIntegerField':(0,32767),25 'PositiveIntegerField':(0,2147483647),26 }27 12、models.IPAddressField 字串類型(ip4Regex)28 13、models.GenericIPAddressField 字串類型(ip4和ip6是可選的)29 參數protocol可以是:both、ipv4、ipv630 驗證時,會根據設定報錯31 14、models.NullBooleanField 允許為空白的布爾類型32 15、models.PositiveIntegerFiel 正Integer33 16、models.PositiveSmallIntegerField 正smallInteger34 17、models.SlugField 減號、底線、字母、數字35 18、models.SmallIntegerField 數字36 資料庫中的欄位有:tinyint、smallint、int、bigint37 19、models.TextField 字串=longtext38 20、models.TimeField 時間 HH:MM[:ss[.uuuuuu]]39 21、models.URLField 字串,地址Regex40 22、models.BinaryField 二進位41 23、models.ImageField圖片42 24、models.FilePathField檔案更多欄位
參數解釋:
1 1、null=True 2 資料庫中欄位是否可以為空白 3 2、blank=True 4 django的Admin中添加資料時是否可允許空值 5 3、primary_key =False 6 主鍵,對AutoField設定主鍵後,就會代替原來的自增 id 列 7 4、auto_now 和 auto_now_add 8 auto_now 自動建立---無論添加或修改,都是當前操作的時間 9 auto_now_add 自動建立---永遠是建立時的時間10 5、choices11 GENDER_CHOICE =(12 (u'M', u'Male'),13 (u'F', u'Female'),14 )15 gender = models.CharField(max_length=2,choices = GENDER_CHOICE)16 6、max_length17 7、default 預設值18 8、verbose_name Admin中欄位的顯示名稱19 9、name|db_column 資料庫中的欄位名稱20 10、unique=True 不允許重複21 11、db_index =True 資料庫索引22 12、editable=True 在Admin裡是否可編輯23 13、error_messages=None 錯誤提示24 14、auto_created=False 自動建立25 15、help_text 在Admin中提示協助資訊26 16、validators=[]27 17、upload-to
參數解釋
進行資料的操作
查:
models.UserInfo.objects.all()
models.UserInfo.objects.all().values('user') #只取user列
models.UserInfo.objects.all().values_list('id','user') #取出id和user列,並產生一個列表
models.UserInfo.objects.get(id=1) #取id=1的資料
models.UserInfo.objects.get(user='rose') #取user=‘rose’的資料
增:models.UserInfo.objects.create(user='rose',pwd='123456')
或者obj = models.UserInfo(user='rose',pwd='123456')obj.save()或者dic = {'user':'rose','pwd':'123456'}models.UserInfo.objects.create(**dic)
刪:models.UserInfo.objects.filter(user='rose').delete() 改: models.UserInfo.objects.filter(user='rose').update(pwd='520')或者obj = models.UserInfo.objects.get(user='rose')obj.pwd = '520'obj.save() 例舉常用方法:
1 # 擷取個數 2 # 3 # models.Tb1.objects.filter(name='seven').count() 4 # 大於,小於 5 # 6 # models.Tb1.objects.filter(id__gt=1) # 擷取id大於1的值 7 # models.Tb1.objects.filter(id__lt=10) # 擷取id小於10的值 8 # models.Tb1.objects.filter(id__lt=10, id__gt=1) # 擷取id大於1 且 小於10的值 9 # in10 #11 # models.Tb1.objects.filter(id__in=[11, 22, 33]) # 擷取id等於11、22、33的資料12 # models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in13 # contains14 #15 # models.Tb1.objects.filter(name__contains="ven")16 # models.Tb1.objects.filter(name__icontains="ven") # icontains大小寫不敏感17 # models.Tb1.objects.exclude(name__icontains="ven")18 # range19 #20 # models.Tb1.objects.filter(id__range=[1, 2]) # 範圍bettwen and21 # 其他類似22 #23 # startswith,istartswith, endswith, iendswith,24 # order by25 #26 # models.Tb1.objects.filter(name='seven').order_by('id') # asc27 # models.Tb1.objects.filter(name='seven').order_by('-id') # desc28 # limit 、offset29 #30 # models.Tb1.objects.all()[10:20]31 # group by32 from django.db.models import Count, Min, Max, Sum33 # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))34 # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"常用方法
二、詳解常用欄位
models.DateTimeField 日期類型 datetime參數,auto_now = True :則每次更新都會更新這個時間auto_now_add 則只是第一次建立添加,之後的更新不再改變。
1 class UserInfo(models.Model):2 name = models.CharField(max_length=32)3 ctime = models.DateTimeField(auto_now=True)4 uptime = models.DateTimeField(auto_now_add=True)
1 from app01 import models2 def home(request):3 models.UserInfo.objects.create(name='yangmv')4 after = models.UserInfo.objects.all()5 print after[0].ctime6 return render(request, 'app01/home.html')
表結構的修改表結構修改後,原來表中已存在的資料,就會出現結構混亂,makemigrations更新表的時候就會出錯解決方案:1、新增加的欄位,設定允許為空白。產生表的時候,之前資料新增加的欄位就會為空白。(null=True允許資料庫中為空白,blank=True允許admin後台中為空白)2、新增加的欄位,設定一個預設值。產生表的時候,之前的資料新增加欄位就會應用這個預設值
1 from django.db import models2 3 # Create your models here.4 class UserInfo(models.Model):5 name = models.CharField(max_length=32)6 ctime = models.DateTimeField(auto_now=True)7 uptime = models.DateTimeField(auto_now_add=True)8 email = models.EmailField(max_length=32,null=True)9 email1 = models.EmailField(max_length=32,default='rose@qq.com')
執行makemigrations, migrate 後。老資料會自動應用新增加的規則
models.ImageField 圖片
models.GenericIPAddressField IP
ip = models.GenericIPAddressField(protocol="ipv4",null=True,blank=True)
img = models.ImageField(null=True,blank=True,upload_to="upload")
常用參數
選擇下拉框 choices
1 class UserInfo(models.Model):2 USER_TYPE_LIST = (3 (1,'user'),4 (2,'admin'),5 )6 user_type = models.IntegerField(choices=USER_TYPE_LIST,default=1)
2、連表結構
- 一對多:models.ForeignKey(其他表)
- 多對多:models.ManyToManyField(其他表)
- 一對一:models.OneToOneField(其他表)
應用情境:
- 一對多:當一張表中建立一行資料時,有一個單選的下拉框(可以被重複選擇)
例如:建立使用者資訊時候,需要選擇一個使用者類型【普通使用者】【金牌使用者】【鉑金使用者】等。
- 多對多:在某表中建立一行資料是,有一個可以多選的下拉框
例如:建立使用者資訊,需要為使用者指定多個愛好
- 一對一:在某表中建立一行資料時,有一個單選的下拉框(下拉框中的內容被用過一次就消失了
例如:原有含10列資料的一張表儲存相關資訊,經過一段時間之後,10列無法滿足需求,需要為原來的表再添加5列資料
一對多:
1 from django.db import models 2 3 4 # Create your models here. 5 class UserType(models.Model): 6 name = models.CharField(max_length=50) 7 class UserInfo(models.Model): 8 username = models.CharField(max_length=50) 9 password = models.CharField(max_length=50)10 email = models.EmailField()11 user_type = models.ForeignKey('UserType')
這是UserInfo表,可以通過外鍵,對應到UserType表的ID
這是User_Type表的資料
多對多:
1 from django.db import models 2 3 4 # Create your models here. 5 class UserType(models.Model): 6 name = models.CharField(max_length=50) 7 class UserInfo(models.Model): 8 username = models.CharField(max_length=50) 9 password = models.CharField(max_length=50)10 email = models.EmailField()11 user_type = models.ForeignKey('UserType') 12 class UserGroup(models.Model):13 GroupName = models.CharField(max_length=50)14 user = models.ManyToManyField("UserInfo")
Django model會自動建立第3張關係表,用於對應UserInfo_id 和UserGroup_id
UserInfo表如上所示:
UserGroup表
Django自動產生的對應關係表
userinfo_id = 1 為 Boss,屬於1(使用者組A)
一對一: (一對多增加了不能重複)
1 from django.db import models 2 3 4 # Create your models here. 5 class UserType(models.Model): 6 name = models.CharField(max_length=50) 7 class UserInfo(models.Model): 8 username = models.CharField(max_length=50) 9 password = models.CharField(max_length=50)10 email = models.EmailField()11 user_type = models.ForeignKey('UserType') 12 class UserGroup(models.Model):13 GroupName = models.CharField(max_length=50)14 user = models.ManyToManyField("UserInfo") 15 class Admin(models.Model):16 Address = models.CharField()17 user_info_address = models.OneToOneField('UserInfo')