pip install mysql-python
pip install pymysql
create database test2 charset=utf8
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test2', 'USER': '用戶名', 'PASSWORD': '密碼', 'HOST': '數據庫服務器ip,本地可使用localhost', 'PORT': '端口,默認爲3306', } }
1. 在models.py中定義模型類,要求繼承自models.Modelhtml
2. 把應用加入settings.py文件的installed_app項python
3. 生成遷移文件mysql
4. 執行遷移生成表git
5. 使用模型類進行crud操做sql
python manage.py inspectdb > booktest/models.py
導入from django.db import models數據庫
經過models.Field建立字段類型的對象,賦值給屬性django
若是不指定,一個主鍵字段將自動添加到模型中緩存
DecimalField.max_digits:位數總數服務器
DecimalField.decimal_places:小數點後的數字位數app
參數DateField.auto_now:每次保存對象時,自動設置該字段爲當前時間,用於"最後一次修改"的時間戳,它老是使用當前日期,默認爲false
參數DateField.auto_now_add:當對象第一次被建立時自動設置當前時間,用於建立的時間戳,它老是使用當前日期,默認爲false
該字段默認對應的表單控件是一個TextInput. 在管理員站點添加了一個JavaScript寫的日曆控件,和一個「Today"的快捷按鈕,包含了一個額外的invalid_date錯誤消息鍵
auto_now_add, auto_now, and default 這些設置是相互排斥的,他們之間的任何組合將會發生錯誤的結果
bookinfo.heroinfo_set
heroinfo.bookinfo
heroinfo.book_id
<app_name>_<model_name> class Meta(): db_table = 'HeroInfo'
class BookInfo(models.Model): ... class Meta(): ordering = ['id']
class BookInfo(models.Model): ... class Meta(): ordering = ['-id']
class BookInfo(models.Model): btitle = models.CharField(max_length=20) bpub_date = models.DateTimeField() bread = models.IntegerField(default=0) bcommet = models.IntegerField(default=0) isDelete = models.BooleanField(default=False)
class HeroInfo(models.Model): hname = models.CharField(max_length=20) hgender = models.BooleanField(default=True) isDelete = models.BooleanField(default=False) hcontent = models.CharField(max_length=100) hbook = models.ForeignKey('BookInfo')
insert into booktest_bookinfo(btitle,bpub_date,bread,bcommet,isDelete) values ('射鵰英雄傳','1980-5-1',12,34,0), ('天龍八部','1986-7-24',36,40,0), ('笑傲江湖','1995-12-24',20,80,0), ('雪山飛狐','1987-11-11',58,24,0)
insert into booktest_heroinfo(hname,hgender,hbook_id,hcontent,isDelete) values ('郭靖',1,1,'降龍十八掌',0), ('黃蓉',0,1,'打狗棍法',0), ('黃藥師',1,1,'彈指神通',0), ('歐陽鋒',1,1,'蛤蟆功',0), ('梅超風',0,1,'九陰白骨爪',0), ('喬峯',1,2,'降龍十八掌',0), ('段譽',1,2,'六脈神劍',0), ('虛竹',1,2,'天山六陽掌',0), ('王語嫣',0,2,'神仙姐姐',0), ('令狐沖',1,3,'獨孤九劍',0), ('任盈盈',0,3,'彈琴',0), ('嶽不羣',1,3,'華山劍法',0), ('東方不敗',0,3,'葵花寶典',0), ('胡斐',1,4,'胡家刀法',0), ('苗若蘭',0,4,'黃衣',0), ('程靈素',0,4,'醫術',0), ('袁紫衣',0,4,'六合拳',0)
class BookInfo(models.Model): ... books = models.Manager()
class BookInfoManager(models.Manager): def get_queryset(self): return super(BookInfoManager, self).get_queryset().filter(isDelete=False) class BookInfo(models.Model): ... books = BookInfoManager()
class BookInfo(models.Model): ... @classmethod def create(cls, title, pub_date): book = cls(btitle=title, bpub_date=pub_date) book.bread=0 book.bcommet=0 book.isDelete = False return book 引入時間包:from datetime import * 調用:book=BookInfo.create("hello",datetime(1980,10,11)); 保存:book.save()
class BookInfoManager(models.Manager): def create_book(self, title, pub_date): book = BookInfo() book.btitle = title book.bpub_date = pub_date book.bread=0 book.bcommet=0 book.isDelete = False return book class BookInfo(models.Model): ... books = BookInfoManager() 調用:book=BookInfo.books.create_book("abc",datetime(1980,1,1)) 保存:book.save() # 在方式二中,能夠調用self.create()建立並保存對象,不須要再手動save() class BookInfoManager(models.Manager): def create_book(self, title, pub_date): book = self.create(btitle = title,bpub_date = pub_date,bread=0,bcommet=0,isDelete = False) return book class BookInfo(models.Model): ... books = BookInfoManager() 調用:book=Book.books.create_book("abc",datetime(1980,1,1)) 查看:book.pk
filter(鍵1=值1,鍵2=值2)
等價於
filter(鍵1=值1).filter(鍵2=值2)
print([e.title for e in Entry.objects.all()]) print([e.title for e in Entry.objects.all()])
querylist=Entry.objects.all() print([e.title for e in querylist]) print([e.title for e in querylist])
# exact:表示判等,大小寫敏感;若是沒有寫「 比較運算符」,表示判等 filter(isDelete=False) # contains:是否包含,大小寫敏感 exclude(btitle__contains='傳') # startswith、endswith:以value開頭或結尾,大小寫敏感 exclude(btitle__endswith='傳') # isnull、isnotnull:是否爲null filter(btitle__isnull=False) # 在前面加個i表示不區分大小寫,如iexact、icontains、istarswith、iendswith # in:是否包含在範圍內 filter(pk__in=[1, 2, 3, 4, 5]) # gt、gte、lt、lte:大於、大於等於、小於、小於等於 filter(id__gt=3) # year、month、day、week_day、hour、minute、second:對日期間類型的屬性進行運算 filter(bpub_date__year=1980) filter(bpub_date__gt=date(1980, 12, 31)) # 跨關聯關係的查詢:處理join查詢 # 語法:模型類名 <屬性名> <比較> # 注:能夠沒有__<比較>部分,表示等於,結果同inner join # 可雙向使用,即在關聯的兩個模型中均可以使用 filter(heroinfo_ _hcontent_ _contains='八') # 查詢的快捷方式:pk,pk表示primary key,默認的主鍵是id filter(pk__lt=6)
from django.db.models import Max maxDate = list.aggregate(Max('bpub_date'))
count = list.count()
# 可使用模型的字段A與字段B進行比較,若是A寫在了等號的左邊,則B出如今等號的右邊,須要經過F對象構造 list.filter(bread__gte=F('bcommet')) # django支持對F()對象使用算數運算 list.filter(bread__gte=F('bcommet') * 2) # F()對象中還能夠寫做「模型類__列名」進行關聯查詢 list.filter(isDelete=F('heroinfo__isDelete')) # 對於date/time字段,可與timedelta()進行運算 list.filter(bpub_date__lt=F('bpub_date') + timedelta(days=1))
from django.db.models import Q list.filter(Q(pk_ _lt=6))
list.filter(pk_ _lt=6).filter(bcommet_ _gt=10) list.filter(Q(pk_ _lt=6) | Q(bcommet_ _gt=10))
list.filter(~Q(pk__lt=6))
class AreaInfo(models.Model): atitle = models.CharField(max_length=20) aparent = models.ForeignKey('self', null=True, blank=True) )
上級對象:area.aparent
下級對象:area.areainfo_set.all()
from models import AreaInfo def area(request): area = AreaInfo.objects.get(id=10) context = {'area': area} return render(request, 'booktest/area.html', context)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>地區</title> </head> <body> <p>當前地區:{{area.atitle}}</p> <hr /> <p>上級地區:{{area.aparent.atitle}}</p> <hr /> 下級地區: <ul> {%for a in area.areainfo_set.all%} <li>{{a.atitle}}</li> {%endfor%} </ul> </body> </html>
urlpatterns = [ url(r'^area/$', views.area, name='area') ]