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') ]