Django 学习
urls.py 路由系统
from django.conf.urls import url,include
from django.contrib import admin
from web import views,urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^list/(\d*)/',views.list),
url(r'^adm/(\d){4}/(\d){2}/',views.adm),
url(r'^login/(?P<name>\d*)/',views.login),
url(r'^login/(?P<name>\d*)/',views.login,{'id':222}),
url(r'^feng/',include('web.urls')),
]
{{ yourPorn }} <hr/> {{ name_list }} <hr/> <ul> {% for k,v in name_list.items %} {% if v == 'IT' %} <li style="background-color: springgreen;width: 80px">{{ k }}::{{ v }}</li> {% else %} <li>{{ k }}::{{ v }}</li> {% endif %} {% endfor %} </ul>
1. 创建数据库-settings 连接mysql的配置文件 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'fengjian', 'USER': 'fengjian', 'PASSWORD': '123456', 'HOST': '172.16.230.151', 'PORT': '3306', } } 2.在settings 的INSTALLED_APPS添加app(web)的models 路径 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', ] 3 创建model,继承自modles.Model类 静态字段 = model.CharField(max_length=50) 4.执行数据库 python manage.py makemigrations python manage.py migrate
常用的models字段有, models.CharField, models.BooleanField, models.IntegerField,
models.TextField, models.DatetimeField
外键 一对多 class UserType(models.Model): name = models.CharField(max_length=20) class UserInfo(models.Model): username = models.CharField(max_length=30) password = models.CharField(max_length=30) gender = models.BooleanField(default=True) age = models.IntegerField(default=22) memo = models.TextField(default='xxx') createdata = models.DateTimeField(default='2016-03-23 10:05') typeid = models.ForeignKey('UserType') 一个用户类型(普通用户,管理员),对应多个用户 UserInfo tableshow id username typeid_id ........ ############################################# 多对多
一个用户可以对应多个组,
class Group(models.Model):
groupname = models.CharField(max_length=30)
class user(models.Model):
username = models.CharField(max_length=30)
email = models.EmailField(default='abc@gmail.com')
user_group_id = models.ManyToManyField('Group')
会单独自动添加出一张表user_group_id
id user_id group_id
其他常用命令: python manage.py runserver 0.0.0.0 python manage.py startapp appname python manage.py syncdb python manage.py makemigrations python manage.py migrate python manage.py createsuperuser
1、models.AutoField 自增列 = int(11) 如果没有的话,默认会生成一个名称为 id 的列,如果要显示的自定义一个自增列,必须将给列设置为主键 primary_key=True。 2、models.CharField 字符串字段 必须 max_length 参数 3、models.BooleanField 布尔类型=tinyint(1) 不能为空,Blank=True 4、models.ComaSeparatedIntegerField 用逗号分割的数字=varchar 继承CharField,所以必须 max_lenght 参数 5、models.DateField 日期类型 date 对于参数,auto_now = True 则每次更新都会更新这个时间;auto_now_add 则只是第一次创建添加,之后的更新不再改变。 6、models.DateTimeField 日期类型 datetime 同DateField的参数 7、models.Decimal 十进制小数类型 = decimal 必须指定整数位max_digits和小数位decimal_places 8、models.EmailField 字符串类型(正则表达式邮箱) =varchar 对字符串进行正则表达式 9、models.FloatField 浮点类型 = double 10、models.IntegerField 整形 11、models.BigIntegerField 长整形 integer_field_ranges = { 'SmallIntegerField': (-32768, 32767), 'IntegerField': (-2147483648, 2147483647), 'BigIntegerField': (-9223372036854775808, 9223372036854775807), 'PositiveSmallIntegerField': (0, 32767), 'PositiveIntegerField': (0, 2147483647), } 12、models.IPAddressField 字符串类型(ip4正则表达式) 13、models.GenericIPAddressField 字符串类型(ip4和ip6是可选的) 参数protocol可以是:both、ipv4、ipv6 验证时,会根据设置报错 14、models.NullBooleanField 允许为空的布尔类型 15、models.PositiveIntegerFiel 正Integer 16、models.PositiveSmallIntegerField 正smallInteger 17、models.SlugField 减号、下划线、字母、数字 18、models.SmallIntegerField 数字 数据库中的字段有:tinyint、smallint、int、bigint 19、models.TextField 字符串=longtext 20、models.TimeField 时间 HH:MM[:ss[.uuuuuu]] 21、models.URLField 字符串,地址正则表达式 22、models.BinaryField 二进制 23、models.ImageField 图片 24、models.FilePathField 文件
常用的models字段有, models.CharField, models.BooleanField, models.IntegerField,
models.TextField, models.DatetimeField
class UserType(models.Model):
name = models.CharField(max_length=20)
class UserInfo(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
sex = models.BooleanField(default=False)
age = models.IntegerField(default=20)
mome = models.TextField(default='xxxx')
data = models.DateTimeField(default='2016-03-22 12:00')
typeid = models.ForeignKey(UserType) #设置与UserType表关联一对多
group_repation = models.ManyToManyfieID(Group) 设置多表关联
auto_now_add 自动创建时间
auto_now 自动生成修改时间
class Asset(models.Model):
hostname = models.CharField(max_length=20)
create_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
1、null=True 数据库中字段是否可以为空 2、blank=True django的 Admin 中添加数据时是否可允许空值 3、primary_key = False 主键,对AutoField设置主键后,就会代替原来的自增 id 列 4、auto_now 和 auto_now_add auto_now 自动创建---无论添加或修改,都是当前操作的时间 auto_now_add 自动创建---永远是创建时的时间 5、choices GENDER_CHOICE = ( (u'M', u'Male'), (u'F', u'Female'), ) gender = models.CharField(max_length=2,choices = GENDER_CHOICE) 6、max_length 7、default 默认值 8、verbose_name Admin中字段的显示名称 9、name|db_column 数据库中的字段名称 10、unique=True 不允许重复 11、db_index = True 数据库索引 12、editable=True 在Admin里是否可编辑 13、error_messages=None 错误提示 14、auto_created=False 自动创建 15、help_text 在Admin中提示帮助信息 16、validators=[] 17、upload-to
models.py ################################# #__coding:utf-8__ from django.shortcuts import render,HttpResponse # Create your views here. from models import Asset def list(request,id): print id return HttpResponse('list') def login(request,name): print name http_html=''' username: <input name=username /> password: <input name=password /> ''' return HttpResponse(http_html) def adm(request,id,id1): print id,id1 return HttpResponse('admin page') # def feng(request): # f=open('feng.html') # data = f.read() # return HttpResponse(data) def index(request): name_info = { 'name': 'fengjian', 'age':'33', 'sex':'boy', 'job':'IT', } return render(request,'index.html', { 'yourPorn':'going to hao daifu', 'name_list':name_info, }) def hosts(request): return render(request,'hosts.html') def Add(request,name): Asset.objects.create(hostname=name) return HttpResponse('ok') def Delete(request,id): Asset.objects.get(id=id).delete() return HttpResponse('ok') def Update(request,id,hostname): # obj = Asset.objects.get(id=id) # obj.hostname = hostname # obj.save()
models.Asset.objects.filter(id__lt=id).update(hostname=hostname) id__lt 小于, id__gt 大于 id__contains 模糊匹配相当于sql中的sql
models.Asset.objects.filter(id__contains=id).update(hostname=hostname)
models.Asset.objects.filter(id__gt=id).update(hostname=hostname
return HttpResponse('ok')
def Select(request,hostname):
seldata = Asset.objects.filter(hostname__contains=hostname)
for item in seldata: print item.hostname
return HttpResponse('ok') #获取所有
def Selall(request):
#seldata = Asset.objects.all() #获取所有
seldata = Asset.objects.all()[0:2] #获取前2个
seldata = Asset.objects.all().order_by('id')
seldata = Asset.objects.all().order_by('-id')
print seldata return HttpResponse(seldata)
#############web.urls.py###################
from django.conf.urls import url
from django.contrib import admin
from web import views
urlpatterns = [ url(r'^admin/', admin.site.urls), #
url(r'^feng/',views.feng),
url(r'^delete/(?P<id>\d*)/',views.Delete),
url(r'^add/(?P<name>\d*)/',views.Add),
url(r'^update/(?P<id>\d*)/(?P<hostname>\w*)/',views.Update),
url(r'^select/(?P<hostname>\w*)/',views.Select),
url(r'^selall/$',views.Selall), ]
2、数据库操作 •增加:创建实例,并调用save •更新:a.获取实例,再sava;b.update(指定列) •删除:a. filter().delete(); b.all().delete() •获取:a. 单个=get(id=1) ;b. 所有 = all() •过滤:filter(name='xxx');filter(name__contains='');(id__in = [1,2,3]) ; icontains(大小写无关的LIKE),startswith和endswith, 还有range(SQLBETWEEN查询)'gt', 'in', 'isnull', 'endswith', 'contains', 'lt', 'startswith', 'iendswith', 'icontains','range', 'istartswith' •排序:order_by("name") =asc ;order_by("-name")=desc •返回第n-m条:第n条[0];前两条[0:2] •指定映射:values •数量:count() •聚合:from django.db.models import Min,Max,Sum objects.all().aggregate(Max('guest_id'))