Django基礎(chǔ)之Model操作步驟(介紹)
一、數(shù)據(jù)庫操作
1、創(chuàng)建model表
基本結(jié)構(gòu):
#coding:Utf8 from django.db import models class userinfo(models.Model): #如果沒有models.AutoField,默認(rèn)會(huì)創(chuàng)建一個(gè)id的自增列 name = models.CharField(max_length=30) email = models.EmailField() memo = models.TextField()
字段解釋:
1、models.AutoField 自增列= int(11) 如果沒有的話,默認(rèn)會(huì)生成一個(gè)名稱為 id 的列,如果要顯示的自定義一個(gè)自增列,必須將給列設(shè)置為主鍵 primary_key=True。 2、models.CharField 字符串字段 必須 max_length 參數(shù) 3、models.BooleanField 布爾類型=tinyint(1) 不能為空,Blank=True 4、models.ComaSeparatedIntegerField 用逗號(hào)分割的數(shù)字=varchar 繼承CharField,所以必須 max_lenght 參數(shù) 5、models.DateField 日期類型 date 對(duì)于參數(shù),auto_now =True則每次更新都會(huì)更新這個(gè)時(shí)間;auto_now_add 則只是第一次創(chuàng)建添加,之后的更新不再改變。 6、models.DateTimeField 日期類型 datetime 同DateField的參數(shù) 7、models.Decimal 十進(jìn)制小數(shù)類型= decimal 必須指定整數(shù)位max_digits和小數(shù)位decimal_places 8、models.EmailField 字符串類型(正則表達(dá)式郵箱)=varchar 對(duì)字符串進(jìn)行正則表達(dá)式 9、models.FloatField 浮點(diǎn)類型= double 10、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 字符串類型(ip4正則表達(dá)式) 13、models.GenericIPAddressField 字符串類型(ip4和ip6是可選的) 參數(shù)protocol可以是:both、ipv4、ipv6 驗(yàn)證時(shí),會(huì)根據(jù)設(shè)置報(bào)錯(cuò) 14、models.NullBooleanField 允許為空的布爾類型 15、models.PositiveIntegerFiel 正Integer 16、models.PositiveSmallIntegerField 正smallInteger 17、models.SlugField 減號(hào)、下劃線、字母、數(shù)字 18、models.SmallIntegerField 數(shù)字 數(shù)據(jù)庫中的字段有:tinyint、smallint、int、bigint 19、models.TextField 字符串=longtext 20、models.TimeField 時(shí)間 HH:MM[:ss[.uuuuuu]] 21、models.URLField 字符串,地址正則表達(dá)式 22、models.BinaryField 二進(jìn)制 23、models.ImageField圖片 24、models.FilePathField文件 更多字段
參數(shù)解釋:
1、null=True 數(shù)據(jù)庫中字段是否可以為空 2、blank=True django的Admin中添加數(shù)據(jù)時(shí)是否可允許空值 3、primary_key =False 主鍵,對(duì)AutoField設(shè)置主鍵后,就會(huì)代替原來的自增 id 列 4、auto_now 和 auto_now_add auto_now 自動(dòng)創(chuàng)建---無論添加或修改,都是當(dāng)前操作的時(shí)間 auto_now_add 自動(dòng)創(chuàng)建---永遠(yuǎn)是創(chuàng)建時(shí)的時(shí)間 5、choices GENDER_CHOICE =( (u'M', u'Male'), (u'F', u'Female'), ) gender = models.CharField(max_length=2,choices = GENDER_CHOICE) 6、max_length 7、default 默認(rèn)值 8、verbose_name Admin中字段的顯示名稱 9、name|db_column 數(shù)據(jù)庫中的字段名稱 10、unique=True 不允許重復(fù) 11、db_index =True 數(shù)據(jù)庫索引 12、editable=True 在Admin里是否可編輯 13、error_messages=None 錯(cuò)誤提示 14、auto_created=False 自動(dòng)創(chuàng)建 15、help_text 在Admin中提示幫助信息 16、validators=[] 17、upload-to 參數(shù)解釋
進(jìn)行數(shù)據(jù)的操作
查:
models.UserInfo.objects.all()
models.UserInfo.objects.all().values('user') #只取user列
models.UserInfo.objects.all().values_list('id','user') #取出id和user列,并生成一個(gè)列表
models.UserInfo.objects.get(id=1) #取id=1的數(shù)據(jù)
models.UserInfo.objects.get(user='rose') #取user=‘rose'的數(shù)據(jù)
增:
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()
例舉常用方法:
# 獲取個(gè)數(shù) # # 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的數(shù)據(jù) # 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
參數(shù),
auto_now = True :則每次更新都會(huì)更新這個(gè)時(shí)間
auto_now_add 則只是第一次創(chuàng)建添加,之后的更新不再改變。
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')
表結(jié)構(gòu)的修改
表結(jié)構(gòu)修改后,原來表中已存在的數(shù)據(jù),就會(huì)出現(xiàn)結(jié)構(gòu)混亂,makemigrations更新表的時(shí)候就會(huì)出錯(cuò)
解決方法:
1、新增加的字段,設(shè)置允許為空。生成表的時(shí)候,之前數(shù)據(jù)新增加的字段就會(huì)為空。(null=True允許數(shù)據(jù)庫中為空,blank=True允許admin后臺(tái)中為空)
2、新增加的字段,設(shè)置一個(gè)默認(rèn)值。生成表的時(shí)候,之前的數(shù)據(jù)新增加字段就會(huì)應(yīng)用這個(gè)默認(rèn)值
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')
執(zhí)行makemigrations, migrate 后。老數(shù)據(jù)會(huì)自動(dòng)應(yīng)用新增加的規(guī)則
models.ImageField 圖片
models.GenericIPAddressField IP
ip = models.GenericIPAddressField(protocol="ipv4",null=True,blank=True)img = models.ImageField(null=True,blank=True,upload_to="upload")
常用參數(shù)
選擇下拉框 choices
class UserInfo(models.Model): USER_TYPE_LIST = ( (1,'user'), (2,'admin'), ) user_type = models.IntegerField(choices=USER_TYPE_LIST,default=1)
2、連表結(jié)構(gòu)
•一對(duì)多:models.ForeignKey(其他表)
•多對(duì)多:models.ManyToManyField(其他表)
•一對(duì)一:models.OneToOneField(其他表)
應(yīng)用場(chǎng)景:
•一對(duì)多:當(dāng)一張表中創(chuàng)建一行數(shù)據(jù)時(shí),有一個(gè)單選的下拉框(可以被重復(fù)選擇)
例如:創(chuàng)建用戶信息時(shí)候,需要選擇一個(gè)用戶類型【普通用戶】【金牌用戶】【鉑金用戶】等。
•多對(duì)多:在某表中創(chuàng)建一行數(shù)據(jù)是,有一個(gè)可以多選的下拉框
例如:創(chuàng)建用戶信息,需要為用戶指定多個(gè)愛好
•一對(duì)一:在某表中創(chuàng)建一行數(shù)據(jù)時(shí),有一個(gè)單選的下拉框(下拉框中的內(nèi)容被用過一次就消失了
例如:原有含10列數(shù)據(jù)的一張表保存相關(guān)信息,經(jīng)過一段時(shí)間之后,10列無法滿足需求,需要為原來的表再添加5列數(shù)據(jù)
一對(duì)多:
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表,可以通過外鍵,對(duì)應(yīng)到UserType表的ID
這是User_Type表的數(shù)據(jù)
多對(duì)多:
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會(huì)自動(dòng)創(chuàng)建第3張關(guān)系表,用于對(duì)應(yīng)UserInfo_id 和UserGroup_id
UserInfo表如上所示:
UserGroup表
Django自動(dòng)生成的對(duì)應(yīng)關(guān)系表
userinfo_id = 1 為 Boss,屬于1(用戶組A)
一對(duì)一: (一對(duì)多增加了不能重復(fù))
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基礎(chǔ)之Model操作步驟(介紹)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- django框架model orM使用字典作為參數(shù),保存數(shù)據(jù)的方法分析
- django模型中的字段和model名顯示為中文小技巧分享
- django模型層(model)進(jìn)行建表、查詢與刪除的基礎(chǔ)教程
- Django中的Model操作表的實(shí)現(xiàn)
- Django中Model的使用方法教程
- Pycharm 操作Django Model的簡(jiǎn)單運(yùn)用方法
- Django項(xiàng)目中model的數(shù)據(jù)處理以及頁面交互方法
- Django 根據(jù)數(shù)據(jù)模型models創(chuàng)建數(shù)據(jù)表的實(shí)例
- 基于Django的ModelForm組件(詳解)
- django 將model轉(zhuǎn)換為字典的方法示例
- Django model序列化為json的方法示例
- Python Web框架之Django框架Model基礎(chǔ)詳解
相關(guān)文章
django前端頁面下拉選擇框默認(rèn)值設(shè)置方式
這篇文章主要介紹了django前端頁面下拉選擇框默認(rèn)值設(shè)置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-08-08python web自制框架之接受url傳遞過來的參數(shù)實(shí)例
今天小編就為大家分享一篇python web自制框架之接受url傳遞過來的參數(shù)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12Pycharm添加虛擬解釋器報(bào)錯(cuò)問題解決方案
這篇文章主要介紹了Pycharm添加虛擬解釋器報(bào)錯(cuò)問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10Python導(dǎo)入Excel數(shù)據(jù)表的幾種實(shí)現(xiàn)方式
在Python中可以使用許多庫來處理Excel文件,下面這篇文章主要給大家介紹了關(guān)于Python導(dǎo)入Excel數(shù)據(jù)表的幾種實(shí)現(xiàn)方式,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01python根據(jù)距離和時(shí)長計(jì)算配速示例
這篇文章主要介紹了python根據(jù)距離和時(shí)長計(jì)算配速示例,需要的朋友可以參考下2014-02-02python實(shí)現(xiàn)圖書館搶座(自動(dòng)預(yù)約)功能的示例代碼
這篇文章主要介紹了python實(shí)現(xiàn)圖書館搶座(自動(dòng)預(yù)約)功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09Python將內(nèi)容進(jìn)行base64編碼與解碼實(shí)現(xiàn)
本文主要介紹了Python將內(nèi)容進(jìn)行base64編碼與解碼實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03eclipse創(chuàng)建python項(xiàng)目步驟詳解
在本篇內(nèi)容里小編給大家分享了關(guān)于eclipse創(chuàng)建python項(xiàng)目的具體步驟和方法,需要的朋友們跟著學(xué)習(xí)下。2019-05-05jupyter 實(shí)現(xiàn)notebook中顯示完整的行和列
這篇文章主要介紹了jupyter 實(shí)現(xiàn)notebook中顯示完整的行和列,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04