day23 Model 操做,Form 验证以及序列化操做

 

 

 

 

 

 

 

 

 

 

 

 

 

Model 操做html

1建立数据库表python

     定制表名:ajax

     

      普通索引:
            建立两个普通索引,这样就会生成两个索引文件

     

   联合索引:
          为了只生成一个索引文件,才建立的联合索引,联合索引的坏处就是必须按顺序从左匹配,只要不是从最左列开始查询的数据就不会走索引。

      联合惟一索引:sql

          只是在联合索引的基础上加了一个unique =True数据库

 

 数据库的查找:django

外键的正向查找:json

 

反向查找:app

 

反向查找指定字段数据:函数

 

指定反向查找的别名:性能

 

 在删除外键约束的表中的数据时,是否删除另外一张表在使用此数据的数据:

 

 判读数据库中的数据是否为空:

like

between

 

 

 

 

统计,求和,最大值,最小值

 

 

 

 

 

 

 

 

 

 

若是你在取这些结果中没有的其余列的数据,Django 会再去数据库操做,可是这样性能就不行了。

 

 本身指定链接那个数据库:

 

 等于:

 

 

 

性能相关:

 正常的取会循环一次取一次ut里的name  性能不行,因此须要加上  就会一次全取出来,能够加参数来选择取哪一个关联表的数据

 

指定ut 链接表:

 

只获取必须数据:

 

 

 

截取时间,生成想获得的格式:


更细粒度的截取及时区转换:

 

执行原生sql:

 

 

 

 

 

 

 

 

 Form 验证:

 

 

 Form 功能:

 

 

 建立一个完整的数据,为静态的数据,当须要修改时就须要修改此class:

 

从数据库获取数据,只是第一次会获取最新数据,也就是说数据库在更新后须要重启程序:

 

重构下from:
不须要重启:

 

 

 实践:

1 forms:

 

from django import forms
from django.forms import fields
from django.forms import widgets
from app01 import models
class UserInfoForm(forms.Form):
    user = fields.CharField(
        required=False,
        widget=widgets.Textarea(attrs={'class':'user'})
    )
    pwd = fields.CharField(
        max_length=12,
        widget=widgets.PasswordInput(attrs={'class':'pwd'})
    )
    #1
    user_type = fields.ChoiceField(
        choices=[],
        widget=widgets.Select
    )
    #2
    user_type2 = fields.CharField(
       widget=widgets.Select(choices=[])
    )
    def __init__(self,*args,**kwargs):
        super(UserInfoForm,self).__init__(*args,**kwargs)
        self.fields['user_type'].choices = models.UserType.objects.values_list('id','name')
        self.fields['user_type2'].widget.choices = models.UserType.objects.values_list('id','name')

views:

from django.shortcuts import render
# Create your views here.
def inedex(request):
    from  app01.forms import UserInfoForm
    obj = UserInfoForm()
    return render(request,'index.html',{'obj':obj})

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>{{ obj.user }}</p>
    <p>{{ obj.pwd }}</p>
    <p>{{ obj.user_type }}</p>
    <p>{{ obj.user_type2 }}</p>
</body>
</html>

  

传入参数设置默认值(初始化操做,当打开页面时,select框选择的结果):

 

form 的更深层次验证,自定义验证:

 

 

 

 

 
错误信息捕获:

 

 

总结:

 

 

 序列化操做:

当一个数据不全是python 的数据类型,而是有其余的数据类型,json 就不能序列化此数据,因此须要更细粒度的控制:

使用json 的 default 函数执行细粒度的操做:

给ajax 返回数据时要返回json 可是有一些数据是Django 特有的数据类型,因此须要自定义函数来处理这些数据:

 

 

 

 

 

相关文章
相关标签/搜索