django基础篇03-阶段总结
1.django的生命周期:
url -> 路由系统 -> 视图函数(获取模版 + 数据 =>渲染) -> 返回字符串
2.路由系统:
/index/ ->函数或类.as_view() /detail/(\d) ->函数(参数)或 类.as_view()(参数) /detail/(?P<nid>\d+) ->函数(参数)或 类.as_view()(参数) /detail/ -> include('app01.urls') /detail/ name='a1' -> include('app01.urls')
视图views.py
from django.shortcuts imoport reverse
# 获取原路径
reverse('a1')
模版
{% url 'a1' %}
3. 视图
FBV:函数 path(r'index',views.index)
def index(request,*args,**kwargs):
pass
CBV:类 path(r'index',views.Index.as_view())
class Index(views.view):
pass
获取用户的数据:
request.GET.get(xxx) request.POST.get(xxx) reqest.FILES.get(xxxx) obj = request.FILES.get('xxx') f = open('simple01.txt','wb') for chunk in obj.chunks(): f.write(chunk) f.close() # checkbox的值的获取 request.GET.getlist('xxx'
给用户返回数据的形式:
render(request,'xxx.html',{arg0:1234,arg1:[1,2,3,4]})
HtppResponse(字符串)
redirect('URL')
4.模版语言
render(request, "模板的文件的路径", {'obj': 1234, 'k1': [1,2,3,4],"k2": {'name': '张扬','age': 73}})
<html> <body> <h1>{{ obj }}</h1> <h1>{{ k1.1 }}</h1> <h1>{{ k2.name }}</h1> {% for v in k2.values %} <h1>{{ v }}</h1> {% endfor %} </body> </html>
5.ORM
a. 创建类和字段
class UserInfo(models.Model): name = models.CharField(max_length=32) age = models.IntgerField()
终端执行:
python3 manage.py makemerigations
python3 manage.py merigate
注意:setting.py文件中,是否INSTALL_APPS是否注册app?
b. 操作
增 以下两种方式都可以
models.UserInfo.objects.create(name='xm01',age=23) obj = models.UserInfo(name='xm02',age=34) obj.save()
删
models.UserInfo.objects.filter(name='xm01').delete()
改
models.UserInfo.objects.filter('xm02').update(name='xm01')
user_info = {'name':'xm03','age':34}
models.UserInfo.object.filter(id__gt=0).update(**user_info)
查
# 查询全部 返回QuerySet对象 models.UserInfo.objects.all() # 条件查询 models.UserInfo.objects.filter(name='xm01') # and的使用 models.UserInfo.objects.filter(name='xm01',age=23) # 查询某些字段 models.UserInfo.objects.all().values('name') # 获取一个对象,如果不存在则报错 models.UserInfo.objects.get(id=1) 或者 如果存在则返回对象,否则返回None obj = models.UserInfo.objects.filter(id=1).first()
外键
# caption 1:普通用户 2:VIP用户 3:游客 class UserType(models.Model): caption = models.CharFileld(max_length=32) class User(models.Model): age = models.IntegerField() name = models.CharField(max_length=64) # 约束 user_type = models.ForeignKey(to='UserType' to_field='id')
6.Ajax
基本使用
<script src="../static/jquery-1.12.4.js"></script> <script> $.ajax({ url:'/orm.html', data: {'account': 'xm02','pwd':'12345678'}, dataType: 'json', traditional: true, success: function (data) { } }) </script>
dataType:返回的参数格式为json数据类型
traditoinal: 参数中包含数组的时候,将此参数设置为true,这样数据才会被传递,当遇到参数为字典的时候,需要通过JSON.stringify(dict)
7.一对多
外键
from django.db import models class UserGroup(models.Model): name = models.CharField(max_length=32) class UserInfo(models.Model): username = models.CharField(max_length=32) pwd = models.CharField(max_length=32) gender = models.CharField(max_length=4) group_type = models.ForeignKey(UserGroup,to_field='id',on_delete=models.CASCADE)
用法:
# 创建数据 # models.UserGroup.objects.create(name='python') # models.UserGroup.objects.create(name='Ruby') # obj = models.UserGroup(name='Object-C') # obj.save() models.UserInfo.objects.create(username='xm01',gender='0',pwd='123456',group_type_id=1) for row in models.UserInfo.objects.all(): print(row.username,row.pwd,row.gender,row.group_type,sep='\t') print(row.group_type.name) obj = models.UserInfo.objects.filter(group_type_id=1) print(obj)
obj = models.UserInfo.objects.filter(id__gt=1).values('username','gender','group_type__name')
print(obj)
for row in obj:
print(row['username'],row['gender'],row['group_type__name'],sep='\t')
# 输出
# xm01 123456 0 UserGroup object (1)
# python
# <QuerySet [<UserInfo: UserInfo object (1)>]>
# <QuerySet [{'username': 'xm02', 'gender': '1', 'group_type__name': 'Ruby'}, {'username': 'xm03', 'gender': '0', 'group_type__name': 'Object-C'}]
# xm02 1 Ruby
# xm03 0 Object-C
UserInfo中的group_type为UserGroup类型的对象,而且外键关联,默认生成 xxx_id字段作为新关联其他模型的字段,如果获取外表的字段,需要通过xxx__op可以获取外表的op字段值
8.多对多
a.自定义关系表
from django.db import models class Host(models.Model): nid = models.AutoField(primary_key=True) hostname = models.CharField(max_length=32, db_index=True) ip = models.GenericIPAddressField(protocol="ipv4", db_index=True) port = models.IntegerField() class Application(models.Model): name = models.CharField(max_length=32) h = models.ManyToManyField(Host)
此时django会自动生成第三张表,表名和表结构如下:
调用方法如下
# obj = Application.objects.filter(id=1).first() # obj.h.add(1) # obj.h.add(2,3) # obj.h.add(*[1,2,3]) # obj.h.remove(1) # obj.h.clear() # obj.h.set([2]) # 返回Host类型的QuerySet对象 qset = obj.h.all() for row in qset: print(row.hostname,row.ip,row.port,sep='\t')