Django基础之Model创建表
一、創(chuàng)建單表
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ù)庫(kù)單表效果如下:
創(chuàng)建用戶(hù):
再次查看表數(shù)據(jù):
二、創(chuàng)建表之一對(duì)多,運(yùn)用外鍵models.ForeignKey("xxx")
models.py
?????name?=?models.CharField(=)
?????country?=?models.CharField(=)
Property(models.Model):
????size?=?models.CharField(=)
????weight?=?models.CharField(=)
????length?=?models.CharField(=)
兩張表Pepole和Property通過(guò)外鍵models.ForeignKey(Pepole)產(chǎn)生關(guān)聯(lián)
默認(rèn)通過(guò)pepole表的id字段產(chǎn)生關(guān)聯(lián),property表生成color_id來(lái)存放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)
也可以通過(guò)指定的字段進(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è)用戶(hù)可以屬于多個(gè)用戶(hù)組,一個(gè)用戶(hù)組可以包含多個(gè)用戶(hù),建立起多對(duì)多的關(guān)聯(lián)關(guān)系
UserGroup表:
User表
關(guān)聯(lián)關(guān)系:
通過(guò)兩張表的user_id和usergroup_id來(lái)創(chuàng)建關(guān)聯(lián)表user_user_to_group
即通過(guò)兩張表的代碼,系統(tǒng)自動(dòng)幫忙創(chuàng)建第三張表(關(guān)聯(lián)表user_user_to_group)
四、數(shù)據(jù)庫(kù)的常用操作
? ? # 增
? ? ①
? ? # models.Tb1.objects.create(c1='xx', c2='oo') ?增加一條數(shù)據(jù),可以接受字典類(lèi)型數(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,支持字典類(lèi)型數(shù)據(jù)
? ? ②
? ? # obj = models.Tb1.objects.get(id=1)
? ? # obj.c1 = '111'
? ? # obj.save() ? ? ? ?# 修改單條數(shù)據(jù)
查詢(xún)例子:
models.py
SimpleModel(models.Model):
? ? username = models.CharField(=)
? ? password = models.CharField(=)
查詢(xún)操作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類(lèi)型,<class?'django.db.models.query.QuerySet'>print?ret.query?#輸出一個(gè)select查詢(xún)語(yǔ)句ret?=?models.SimpleModel.objects.all().values('username')?#只獲取某一個(gè)列數(shù)據(jù),這里獲取username列print?ret,type(ret)?#這里獲取的每一項(xiàng)數(shù)據(jù)類(lèi)型是一個(gè)字典#[{'username':'u'alex''}]?<class?'django.db.models.query.ValueQuerySet'>ret?=?models.SimpleModel.objects.all().values_list('username')?#這里每一項(xiàng)數(shù)據(jù)類(lèi)型就是一個(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
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?jsondic?=?((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語(yǔ)句查詢(xún)結(jié)果就成了從數(shù)據(jù)庫(kù)中獲取數(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ù)庫(kù)的進(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大小寫(xiě)不敏感
# models.Tb1.objects.exclude(name__icontains="ven")
# range
# models.Tb1.objects.filter(id__range=[1, 2]) ? # 范圍bettwen and
# 其他類(lèi)似
# 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"
轉(zhuǎn)載于:https://blog.51cto.com/ucode/1864648
總結(jié)
以上是生活随笔為你收集整理的Django基础之Model创建表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 第六十六篇、OC_Sqlite数据库操作
- 下一篇: STM32中IO口的8中工作模式