Django基礎之Model操作步驟(介紹),djangomodel

來源:互聯網
上載者:User

Django基礎之Model操作步驟(介紹),djangomodel

一、資料庫操作

1、建立model表

基本結構:

#coding:Utf8from django.db import models class userinfo(models.Model): #如果沒有models.AutoField,預設會建立一個id的自增列 name = models.CharField(max_length=30) email = models.EmailField() memo = models.TextField()

欄位解釋:

1、models.AutoField  自增列= int(11)  如果沒有的話,預設會產生一個名稱為 id 的列,如果要顯示的自訂一個自增列,必須將給列設定為主鍵 primary_key=True。2、models.CharField  字串欄位  必須 max_length 參數3、models.BooleanField  布爾類型=tinyint(1)  不可為空,Blank=True4、models.ComaSeparatedIntegerField  用逗號分割的數字=varchar  繼承CharField,所以必須 max_lenght 參數5、models.DateField  日期類型 date  對於參數,auto_now =True則每次更新都會更新這個時間;auto_now_add 則只是第一次建立添加,之後的更新不再改變。6、models.DateTimeField  日期類型 datetime  同DateField的參數7、models.Decimal  十進位小數類型= decimal  必須指定整數位max_digits和小數位decimal_places8、models.EmailField  字串類型(Regex郵箱)=varchar  對字串進行Regex9、models.FloatField  浮點類型= double10、models.IntegerField  整形11、models.BigIntegerField  長整形  integer_field_ranges ={    'SmallIntegerField':(-32768,32767),    'IntegerField':(-2147483648,2147483647),    'BigIntegerField':(-9223372036854775808,9223372036854775807),    'PositiveSmallIntegerField':(0,32767),    'PositiveIntegerField':(0,2147483647),  }12、models.IPAddressField  字串類型(ip4Regex)13、models.GenericIPAddressField  字串類型(ip4和ip6是可選的)  參數protocol可以是:both、ipv4、ipv6  驗證時,會根據設定報錯14、models.NullBooleanField  允許為空白的布爾類型15、models.PositiveIntegerFiel  正Integer16、models.PositiveSmallIntegerField  正smallInteger17、models.SlugField  減號、底線、字母、數字18、models.SmallIntegerField  數字  資料庫中的欄位有:tinyint、smallint、int、bigint19、models.TextField  字串=longtext20、models.TimeField  時間 HH:MM[:ss[.uuuuuu]]21、models.URLField  字串,地址Regex22、models.BinaryField  二進位23、models.ImageField圖片24、models.FilePathField檔案更多欄位

參數解釋:

1、null=True  資料庫中欄位是否可以為空白2、blank=True  django的Admin中添加資料時是否可允許空值3、primary_key =False  主鍵,對AutoField設定主鍵後,就會代替原來的自增 id 列4、auto_now 和 auto_now_add  auto_now 自動建立---無論添加或修改,都是當前操作的時間  auto_now_add 自動建立---永遠是建立時的時間5、choicesGENDER_CHOICE =((u'M', u'Male'),(u'F', u'Female'),)gender = models.CharField(max_length=2,choices = GENDER_CHOICE)6、max_length7、default  預設值8、verbose_name  Admin中欄位的顯示名稱9、name|db_column  資料庫中的欄位名稱10、unique=True  不允許重複11、db_index =True  資料庫索引12、editable=True  在Admin裡是否可編輯13、error_messages=None  錯誤提示14、auto_created=False  自動建立15、help_text  在Admin中提示協助資訊16、validators=[]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()

例舉常用方法:

# 擷取個數 # # models.Tb1.objects.filter(name='seven').count() # 大於,小於 # # models.Tb1.objects.filter(id__gt=1)    # 擷取id大於1的值 # models.Tb1.objects.filter(id__lt=10)    # 擷取id小於10的值 # models.Tb1.objects.filter(id__lt=10, id__gt=1) # 擷取id大於1 且 小於10的值 # in # # models.Tb1.objects.filter(id__in=[11, 22, 33]) # 擷取id等於11、22、33的資料 # models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in # contains # # models.Tb1.objects.filter(name__contains="ven") # models.Tb1.objects.filter(name__icontains="ven") # icontains大小寫不敏感 # models.Tb1.objects.exclude(name__icontains="ven") # range # # models.Tb1.objects.filter(id__range=[1, 2]) # 範圍bettwen and # 其他類似 # # startswith,istartswith, endswith, iendswith, # order by # # models.Tb1.objects.filter(name='seven').order_by('id') # asc # models.Tb1.objects.filter(name='seven').order_by('-id') # desc # limit 、offset # # models.Tb1.objects.all()[10:20] # group by from django.db.models import Count, Min, Max, Sum # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num')) # 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 則只是第一次建立添加,之後的更新不再改變。

class UserInfo(models.Model):  name = models.CharField(max_length=32)  ctime = models.DateTimeField(auto_now=True)  uptime = models.DateTimeField(auto_now_add=True)
 from app01 import models def home(request):  models.UserInfo.objects.create(name='yangmv')  after = models.UserInfo.objects.all()  print after[0].ctime  return render(request, 'app01/home.html')

表結構的修改

表結構修改後,原來表中已存在的資料,就會出現結構混亂,makemigrations更新表的時候就會出錯

解決方案:

1、新增加的欄位,設定允許為空白。產生表的時候,之前資料新增加的欄位就會為空白。(null=True允許資料庫中為空白,blank=True允許admin後台中為空白)

2、新增加的欄位,設定一個預設值。產生表的時候,之前的資料新增加欄位就會應用這個預設值

from django.db import models# Create your models here.class UserInfo(models.Model):  name = models.CharField(max_length=32)  ctime = models.DateTimeField(auto_now=True)  uptime = models.DateTimeField(auto_now_add=True)  email = models.EmailField(max_length=32,null=True)  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

class UserInfo(models.Model):  USER_TYPE_LIST = (   (1,'user'), (2,'admin'), )  user_type = models.IntegerField(choices=USER_TYPE_LIST,default=1)

2、連表結構

•一對多:models.ForeignKey(其他表)
•多對多:models.ManyToManyField(其他表)
•一對一:models.OneToOneField(其他表)

應用情境:

•一對多:當一張表中建立一行資料時,有一個單選的下拉框(可以被重複選擇)

例如:建立使用者資訊時候,需要選擇一個使用者類型【普通使用者】【金牌使用者】【鉑金使用者】等。

•多對多:在某表中建立一行資料是,有一個可以多選的下拉框

例如:建立使用者資訊,需要為使用者指定多個愛好

•一對一:在某表中建立一行資料時,有一個單選的下拉框(下拉框中的內容被用過一次就消失了

例如:原有含10列資料的一張表儲存相關資訊,經過一段時間之後,10列無法滿足需求,需要為原來的表再添加5列資料

一對多:

from django.db import models# Create your models here.class UserType(models.Model): name = models.CharField(max_length=50) class UserInfo(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) email = models.EmailField() user_type = models.ForeignKey('UserType')

這是UserInfo表,可以通過外鍵,對應到UserType表的ID

這是User_Type表的資料

多對多:

from django.db import models# Create your models here.class UserType(models.Model): name = models.CharField(max_length=50) class UserInfo(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) email = models.EmailField() user_type = models.ForeignKey('UserType') class UserGroup(models.Model): GroupName = models.CharField(max_length=50) user = models.ManyToManyField("UserInfo")

Django model會自動建立第3張關係表,用於對應UserInfo_id 和UserGroup_id

UserInfo表如上所示:

UserGroup表

Django自動產生的對應關係表

userinfo_id = 1 為 Boss,屬於1(使用者組A)

一對一: (一對多增加了不能重複)

from django.db import models# Create your models here.class UserType(models.Model): name = models.CharField(max_length=50) class UserInfo(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) email = models.EmailField() user_type = models.ForeignKey('UserType') class UserGroup(models.Model): GroupName = models.CharField(max_length=50) user = models.ManyToManyField("UserInfo") class Admin(models.Model): Address = models.CharField() user_info_address = models.OneToOneField('UserInfo')

以上這篇Django基礎之Model操作步驟(介紹)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.