一、創(chuàng)建單表
目前創(chuàng)新互聯(lián)建站已為上1000家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬主機(jī)、網(wǎng)站托管運(yùn)營(yíng)、企業(yè)網(wǎng)站設(shè)計(jì)、日喀則網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。
models.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from __future__ import unicode_literals from django.db import models class UserInfo(models.Model): USER_TYPE_LIST = ( (1,"F"), (2,"M"), ) name = models.CharField(max_length=32,primary_key=True) user_type = models.IntegerField(choices=USER_TYPE_LIST,default=1) ctime = models.DateTimeField(auto_now=True) uptime = models.DateTimeField(auto_now_add=True) email = models.EmailField(max_length=32,null=True) email_default = models.EmailField(max_length=32,default="admin@163.com") ip = models.GenericIPAddressField(protocol='both',null=True,blank=True) img = models.ImageField(null=True,blank=True,upload_to="upload") def __unicode__(self): return self.name
創(chuàng)建數(shù)據(jù)庫單表效果如下:
創(chuàng)建用戶:
再次查看表數(shù)據(jù):
二、創(chuàng)建表之一對(duì)多,運(yùn)用外鍵models.ForeignKey("xxx")
models.py
Pepole(models.Model):
name = models.CharField(=)
country = models.CharField(=)
Property(models.Model):
size = models.CharField(=)
weight = models.CharField(=)
length = models.CharField(=)
兩張表Pepole和Property通過外鍵models.ForeignKey(Pepole)產(chǎn)生關(guān)聯(lián)
默認(rèn)通過pepole表的id字段產(chǎn)生關(guān)聯(lián),property表生成color_id來存放pepole表的id,具體如下:
如果我們?cè)趐epole表內(nèi)生成數(shù)據(jù),則會(huì)出現(xiàn)如下id:
同時(shí)在property表中可以看到關(guān)聯(lián)的項(xiàng)可選數(shù)字為1、2、3、4
那一般什么時(shí)候用外鍵呢?比如我們要?jiǎng)?chuàng)建一個(gè)業(yè)務(wù)線,同時(shí)也要?jiǎng)?chuàng)建一個(gè)主機(jī),但是主機(jī)隸屬于某個(gè)業(yè)務(wù)線中的一部分,所以這個(gè)時(shí)候我們可以采取外鍵的方式創(chuàng)建一對(duì)多表,代碼如下:
class Business(models.Model):
name = models.CharField(max_length=16)
class Host(models.Model):
hostname = models.CharField(max_length=32)
或者
class Business(models.Model):
name = models.CharField(max_length=16)
class Host(models.Model):
hostname = models.CharField(max_length=32)
也可以通過指定的字段進(jìn)行綁定
class Business(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=16,unique=True)
class Host(models.Model):
hostname = models.CharField(max_length=32)
business = models.ForeignKey('Business',to_field='nid')
表Business
表Host
表Host關(guān)聯(lián)字段
三、創(chuàng)建表之多對(duì)多,運(yùn)用models.ManyToManyField('xxxx')
UserGroup(models.Model):
group_name = models.CharField(=)
User(models.Model):
name = models.CharField(=)
email= models.EmailField(=)
user_to_group = models.ManyToManyField()
一個(gè)用戶可以屬于多個(gè)用戶組,一個(gè)用戶組可以包含多個(gè)用戶,建立起多對(duì)多的關(guān)聯(lián)關(guān)系
UserGroup表:
User表
關(guān)聯(lián)關(guān)系:
通過兩張表的user_id和usergroup_id來創(chuàng)建關(guān)聯(lián)表user_user_to_group
即通過兩張表的代碼,系統(tǒng)自動(dòng)幫忙創(chuàng)建第三張表(關(guān)聯(lián)表user_user_to_group)
四、數(shù)據(jù)庫的常用操作
# 增
①
# models.Tb1.objects.create(c1='xx', c2='oo') 增加一條數(shù)據(jù),可以接受字典類型數(shù)據(jù) **kwargs
②
# obj = models.Tb1(c1='xx', c2='oo')
# obj.save()
③
dic = {'c1':'xx','c2':'oo'}
models.Tb1.objects.create(**dic)
# 查
#
# models.Tb1.objects.get(id=123) # 獲取單條數(shù)據(jù),不存在則報(bào)錯(cuò)(不建議)
# models.Tb1.objects.all() # 獲取全部
# models.Tb1.objects.all().first()# 取第一條數(shù)據(jù)
# models.Tb1.objects.filter(name='seven') # 獲取指定條件的數(shù)據(jù)
# 刪
#
# models.Tb1.objects.filter(name='seven').delete() # 刪除指定條件的數(shù)據(jù)
# 改
①
# models.Tb1.objects.filter(name='seven').update(gender='0') # 將指定條件的數(shù)據(jù)更新,均支持 **kwargs,支持字典類型數(shù)據(jù)
②
# obj = models.Tb1.objects.get(id=1)
# obj.c1 = '111'
# obj.save() # 修改單條數(shù)據(jù)
查詢例子:
models.py
SimpleModel(models.Model):
username = models.CharField(=)
password = models.CharField(=)
查詢操作home.py
def index(request): dic = {'username':'pythoner','password':'123!@#'} models.SimpleModel.objects.create(**dic) ret = models.SimpleModel.objects.all() #獲取所有的數(shù)據(jù) print ret #是一個(gè)對(duì)象的列表[<SimpleModel: SimpleModel object>], print type(ret) #輸出結(jié)果為django的一個(gè)QuerySet類型,<class 'django.db.models.query.QuerySet'> print ret.query #輸出一個(gè)select查詢語句 ret = models.SimpleModel.objects.all().values('username') #只獲取某一個(gè)列數(shù)據(jù),這里獲取username列 print ret,type(ret) #這里獲取的每一項(xiàng)數(shù)據(jù)類型是一個(gè)字典 #[{'username':'u'alex''}] <class 'django.db.models.query.ValueQuerySet'> ret = models.SimpleModel.objects.all().values_list('username') #這里每一項(xiàng)數(shù)據(jù)類型就是一個(gè)元組 print ret,type(ret) #[(u'alex',)]<class 'django.db.models.query.ValueList'> obj = HomeForm.ImportForm() return render(request,'home/index.html',{'obj':obj})
get data from file
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'ryan' from django import forms class ImportForm(forms.Form): HOST_TYPE_LIST = ( (1,'物理機(jī)'), (2,'虛擬機(jī)') ) host_type = forms.IntegerField( widget=forms.Select(choices=HOST_TYPE_LIST) ) hostname = forms.CharField(widget=forms.PasswordInput()) import json dic = ((1,"abc"),(2,"abcd"),(3,"abcdef")) f = open('db_admin','w') f.write(json.dumps(dic)) f.close() fr = open("db_admin") data = fr.read() data_tuple = json.loads(data) #從文件中獲取數(shù)據(jù),后期將該部分內(nèi)容改成sql語句查詢結(jié)果就成了從數(shù)據(jù)庫中獲取數(shù)據(jù) admin = forms.IntegerField( widget=forms.Select(choices=data_tuple) ) def __init__(self,*args,**kwargs): super(ImportForm,self).__init__(*args,**kwargs) #執(zhí)行父類的構(gòu)造方法 import json fr = open("db_admin") data = fr.read() data_tuple = json.loads(data) self.fields['admin'].widget.choice = data_tuple
get data from database
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'ryan' from django import forms from app01 import models class ImportForm(forms.Form): HOST_TYPE_LIST = ( (1,'物理機(jī)'), (2,'虛擬機(jī)') ) host_type = forms.IntegerField( widget=forms.Select(choices=HOST_TYPE_LIST) ) hostname = forms.CharField(widget=forms.PasswordInput()) import json dic = ((1,"abc"),(2,"abcd"),(3,"abcdef")) f = open('db_admin','w') f.write(json.dumps(dic)) f.close() fr = open("db_admin") data = fr.read() data_tuple = json.loads(data) #從文件中獲取數(shù)據(jù),后期將該部分內(nèi)容改成sql語句查詢結(jié)果就成了從數(shù)據(jù)庫中獲取數(shù)據(jù) admin = forms.IntegerField( widget=forms.Select(choices=data_tuple) ) def __init__(self,*args,**kwargs): super(ImportForm,self).__init__(*args,**kwargs) self.fields['admin'].widget.choice = models.SimpleModel.objects.all().values_list('id','username')
五、數(shù)據(jù)庫的進(jìn)階操作
# 獲取個(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"
文章名稱:Django基礎(chǔ)之Model創(chuàng)建表
轉(zhuǎn)載源于:http://chinadenli.net/article48/jossep.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、網(wǎng)站制作、響應(yīng)式網(wǎng)站、建站公司、ChatGPT、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)