• django开发、filter操作、处理、多对多,django-forms,ModelForm


    #前端 对后端返回数据进行处理,自带filter

    后端返回:status = "很高兴见到你"  , word=' nice too meet you’

    1-{{ status|length }}  ==6, 长度

    2-{{ word|upper }}  ,大写

    3-{{ tmp_html|safe }},识别html

    4-{{ word|truncatechars:5 }}==ni..., 展示5个字符、其余省略

    5-{{word.0}}  取第一个元素

    #自定义filter,自定义SimpleTag,在app根目录创建templates目录,创建tmpTags .py文件,

    from django import template
    register = template.Library()    #固定写法
    
    #自定义过滤器
    @register.filter
    def demo_filter(x):    #x可以为后端返回的参数
        if x == 1:
            return 'success'
        else:
            return 'faild'

    #前端;
    {% load tmpTags %}
    {{ status|demo_filter }} == success

    @register.filter
    def test_filter(x, y):
    return x + y
    filter最多支持2个参数,管道符左侧为第一个参数,冒号后为第二个参数{{ 1|filter_demo:2 }}

    #自定义simple_tag

    @register.simple_tag
        def simple_tag_demo(x, y,z):
            return x + y + z
     
    {% simple_tag_demo 1 2 3 %} --前端
     simple_tag可以支持多个参数,通过空格进行分格即可

    #models  ORM操作多对多

    class Student(models.Model):
        name = models.CharField(verbose_name='学生姓名',max_length=50)
        age = models.IntegerField(verbose_name='年龄')
        class Meta:
            db_table = 'students'
    
    class Teacher(models.Model):
        name = models.CharField(verbose_name='老师姓名',max_length=50)
        student = models.ManyToManyField(Student,verbose_name='学生')   #创建多对多
        class Meta:
            db_table='teacher'

    数据库中创建了三张表:
    
    

     #写入多对多关系

     多对多关系
    teacher_obj = models.Teacher.objects.get(id=2) # id=1 牛牛 id=2 大师兄
    student_obj = models.Student.objects.get(id=4)
    创建多对多关系 (方法1)
    teacher_obj.student.add(student_obj)
    创建多对多 (方法2)
    add方法可以接收主键id=(student_id)
    teacher_obj.student.add(4)
    #查询多对多-正向查询,查询teacher对应的所有student
    students = teacher_obj.student.all()

    #反向查询,查询student对应的所有teacher
    teachers = student_obj.teacher_set.all()

    #删除多对多关系
    teacher_obj.student.clear() #删除老师对应的所有学生
    teacher_obj.student.remove(2) #删除指定的某个学生
    teacher_obj.student.remove(student_obj)

    # orm 返回的 有两种数据类型  QuerySet   object
    # QuerySet, 支持链式编程,可以在all()后继续.方法

    teachers = models.Teacher.objects.all()
    name = teachers.values('name')  # 过滤字段,获取我们希望获取到字段
    count = teachers.count() # 返回qs的个数
    firstData = teachers.first() # 获取qs中第一个数据 list[0]
    value_name = teachers.values_list('name') # 只返回 要求过滤的字段的 value值不返回key
    # object
    teacher = models.Teacher.objects.get(id=1)
    # print("teacher.name", teacher.name)

    #过滤orm, filter=where
    # teacher = models.Teacher.objects.filter(name__contains='')  # 过滤 模糊查询  == sql %
    # teacher = models.Teacher.objects.filter(name__endswith='') # 过滤 以什么为结尾
    # teacher = models.Teacher.objects.filter(name__startswith='') # 过滤 以什么开头
    # teacher = models.Teacher.objects.filter(name__in=['大师兄','牛牛']) # 过滤 在什么范围内 == sql in条件
    # teacher = models.Teacher.objects.filter(id__gt=1) # 过滤 大于
    # teacher = models.Teacher.objects.filter(id__gte=1) # 过滤 大于等于
    # teacher = models.Teacher.objects.filter(id__lt=2) # 过滤 小于
    # teacher = models.Teacher.objects.filter(id__lte=2) # 过滤 小于等于
    # student = models.Student.objects.filter(id__range=[1,3]) # 过滤 在14之间 between and
    # 排除
    # 除了name=大师兄 其他都查出来
    # teacher = models.Teacher.objects.exclude(name='大师兄')
    # 多条件查询
    # and
    # teacher = models.Teacher.objects.filter(id=1, name='牛牛') # where id=1 and name=牛牛

    #or
    from django.db.models import Q
    # where id=1 or name=大师兄
    # teacher = models.Teacher.objects.filter(Q(id=1) | Q(name='大师兄')) # or | 只要条件成立 就把数据都查出来
    # where id=1 and name=大师兄
    teacher = models.Teacher.objects.filter(Q(id=1) & Q(name='大师兄')) # and & 只要条件成立 就把数据都查出来

    # 取反的功能
    # where id=1 and name!=大师兄
    teacher = models.Teacher.objects.filter(Q(id=1) & ~Q(name='大师兄')) # and & 只要条件成立 就把数据都查出来

    django-forms,后端对前端的数据进行验证

    app下新建forms.py   导入:

    from django import forms
    from django.core.exceptions import ValidationError
    class ArticleForm(forms.Form):
    title = forms.CharField(
    required=True, #是否必填
    error_messages={
    'required':'必填参数未填', #错误信息提示
    }
    )


    在views逻辑中引用
    from user.forms import ArticleForm
    def article(request):
    if request.method == 'GET':
    return render(request,'post.html')
    else:
    articleObj = ArticleForm(request.POST) #实例化form验证器,接受post传过来的数据
    f = articleObj.is_valid() #判断当前写好的验证器是否验证通过, 返回True or false
    print("is_valid",f)
    print(articleObj.errors) #拿到错误信息
    return HttpResponse('ok')

    
    
    def article(request):
    if request.method == 'GET':
    return render(request,'post.html')
    else:
    articleObj = ArticleForm(request.POST) #实例化form验证器,接收post传过来的数据
    f = articleObj.is_valid() #判断当前写好的验证器是否验证通过,返回true or false
    if f:
    print(articleObj.cleaned_data) #验证通过的字段放在cleaned_data中
    msg = '成功'
    else:
    print("is_valid", f)
    print(articleObj.errors)
    print(articleObj.errors.get_json_data()) #拿到错误信息
    msg = articleObj.errors.get_json_data().get('title')[0].get('message') #通过dict方式取,返回给前端
    return HttpResponse(msg)
    return HttpResponse(msg)

    自定义验证条件:
    def test_phone(value):    #自定义
    if len(value) != 11:
    raise ValidationError('手机格式不正确')
    else:
    return value

    class ArticleForm(forms.Form):
    phone = forms.CharField(
    required=True, #是否必填
    validators=[test_phone], #引入自定义验证
    error_messages={
    'required':'必填参数未填', #错误信息提示
    }
    )

    forms中存在钩子函数,验证顺序 3 》2 》1

    def test_phone(value):
    print(3)
    if len(value) != 11:
    raise ValidationError('手机格式不正确')
    else:
    return value

    class ArticleForm(forms.Form):
    phone = forms.CharField(
    required=True, #是否必填
    validators=[test_phone], #自定义验证 #第一步先验证
    error_messages={
    'required':'必填参数未填', #错误信息提示
    }
    )
    #forms中存在钩子函数 clean
    #1-通过cleaned_data验证所有数据 #第三部验证
    def clean(self): #froms
    print(1)
    return self.cleaned_data

    #2-针对个别字段验证
    def clean_phone(self): #针对title字段验证 #第二步验证
    print(2)
    return self.cleaned_data.get('phone')

    model+form, 结合数据库表进行验证
    class StudentForm(forms.ModelForm):
    class Meta:
    model = models.Student #创建变了和model建立映射关系
    fields = '__all__' #验证全部字段



    views中逻辑:
    def student(request):
    if request.method == 'GET':
    return render(request,'student.html')
    else:
    studentObj = StudentForm(request.POST)
    f = studentObj.is_valid()
    if f :
    print(studentObj.cleaned_data)
    else:
    print(studentObj.errors)
    return HttpResponse('ok')



     
  • 相关阅读:
    一款前端文件上传工具
    聊一聊最近找工作的感受
    神秘的计算机网络----(1)
    月下无限连?拒绝无休止switch!
    计算机网络---序
    验证码识别
    两数之和
    Sanic框架基础之解决CORS跨域
    Sanic框架进阶之实现异步缓存组件
    asyncio异步模块的21个协程编写实例
  • 原文地址:https://www.cnblogs.com/whcp855/p/13589355.html
Copyright © 2020-2023  润新知