您好,登錄后才能下訂單哦!
一、創建單表
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
創建數據庫單表效果如下:
創建用戶:
再次查看表數據:
二、創建表之一對多,運用外鍵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)產生關聯
默認通過pepole表的id字段產生關聯,property表生成color_id來存放pepole表的id,具體如下:
如果我們在pepole表內生成數據,則會出現如下id:
同時在property表中可以看到關聯的項可選數字為1、2、3、4
那一般什么時候用外鍵呢?比如我們要創建一個業務線,同時也要創建一個主機,但是主機隸屬于某個業務線中的一部分,所以這個時候我們可以采取外鍵的方式創建一對多表,代碼如下:
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)
也可以通過指定的字段進行綁定
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關聯字段
三、創建表之多對多,運用models.ManyToManyField('xxxx')
UserGroup(models.Model):
group_name = models.CharField(=)
User(models.Model):
name = models.CharField(=)
email= models.EmailField(=)
user_to_group = models.ManyToManyField()
一個用戶可以屬于多個用戶組,一個用戶組可以包含多個用戶,建立起多對多的關聯關系
UserGroup表:
User表
關聯關系:
通過兩張表的user_id和usergroup_id來創建關聯表user_user_to_group
即通過兩張表的代碼,系統自動幫忙創建第三張表(關聯表user_user_to_group)
四、數據庫的常用操作
# 增
①
# models.Tb1.objects.create(c1='xx', c2='oo') 增加一條數據,可以接受字典類型數據 **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) # 獲取單條數據,不存在則報錯(不建議)
# models.Tb1.objects.all() # 獲取全部
# models.Tb1.objects.all().first()# 取第一條數據
# models.Tb1.objects.filter(name='seven') # 獲取指定條件的數據
# 刪
#
# models.Tb1.objects.filter(name='seven').delete() # 刪除指定條件的數據
# 改
①
# models.Tb1.objects.filter(name='seven').update(gender='0') # 將指定條件的數據更新,均支持 **kwargs,支持字典類型數據
②
# obj = models.Tb1.objects.get(id=1)
# obj.c1 = '111'
# obj.save() # 修改單條數據
查詢例子:
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() #獲取所有的數據 print ret #是一個對象的列表[<SimpleModel: SimpleModel object>], print type(ret) #輸出結果為django的一個QuerySet類型,<class 'django.db.models.query.QuerySet'> print ret.query #輸出一個select查詢語句 ret = models.SimpleModel.objects.all().values('username') #只獲取某一個列數據,這里獲取username列 print ret,type(ret) #這里獲取的每一項數據類型是一個字典 #[{'username':'u'alex''}] <class 'django.db.models.query.ValueQuerySet'> ret = models.SimpleModel.objects.all().values_list('username') #這里每一項數據類型就是一個元組 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,'物理機'), (2,'虛擬機') ) 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) #從文件中獲取數據,后期將該部分內容改成sql語句查詢結果就成了從數據庫中獲取數據 admin = forms.IntegerField( widget=forms.Select(choices=data_tuple) ) def __init__(self,*args,**kwargs): super(ImportForm,self).__init__(*args,**kwargs) #執行父類的構造方法 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,'物理機'), (2,'虛擬機') ) 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) #從文件中獲取數據,后期將該部分內容改成sql語句查詢結果就成了從數據庫中獲取數據 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')
五、數據庫的進階操作
# 獲取個數
# 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"
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。