• django中的散碎知识


    models之ManytoMany自关联

    from django.shortcuts import render,HttpResponse,redirect
    from app01 import models
    # Create your views here.
    def test(request):
        # models.UserInfo.objects.create(username='zhangsan',password='123',name='张三',gender='1')
        # models.UserInfo.objects.create(username='lisi',password='123',name='李四',gender='1')
        # models.UserInfo.objects.create(username='wangwu',password='123',name='王五',gender='1')
        # models.UserInfo.objects.create(username='xiaohong',password='123',name='小红',gender='2')
        # models.UserInfo.objects.create(username='xiaobai',password='123',name='小白',gender='2')
        # models.UserInfo.objects.create(username='xiaolan',password='123',name='小兰',gender='2')
    
        # zhangsan=models.UserInfo.objects.filter(id=1).first()
        # # print(zhangsan)
        # result=zhangsan.girls.all()
        # print(result)
        # for i in result:
        #     print(i.g.name)
    
    
    
    
        zhangsan=models.UserInfo.objects.filter(id=1).first()
        v=zhangsan.m.all()
        print(v)
        xiaobai=models.UserInfo.objects.filter(id=5).first()
        result=xiaobai.userinfo_set.all()
        print(result)
        return HttpResponse('ssss')
    views.py
    from django.db import models
    
    # Create your models here.
    class UserInfo(models.Model):
        name=models.CharField(max_length=32)
        username=models.CharField(max_length=32)
        password=models.CharField(max_length=32)
        gender_choice=(
            (1,''),
            (2,''),
        )
        gender=models.IntegerField(choices=gender_choice)
        m = models.ManyToManyField('UserInfo')
    # class U2U(models.Model):
    #     b=models.ForeignKey('UserInfo',on_delete=models.PROTECT,related_name='girls')
    #     g=models.ForeignKey('UserInfo',on_delete=models.PROTECT,related_name='boys')
    models.py

    ORM中queryset对象之后返回数据类型:

    1. values返回是字典列表;
    2. values_list返回的是元组列表,
    3. values_list加上

      flat=True之后返回值列表
    4. .first可以取queryset对象

    view.py利用装饰器对页面做session验证:

    from functools import wraps
    def check_login(f):
        @wraps(f)
        def inner(request):
            if request.session.get('is_login'):
                return f(request)
            else:
                return redirect('/login.html/')
        return inner
    view.py
    写出漂亮的博客就是为了以后看着更方便的。
  • 相关阅读:
    redis 命令
    继续node爬虫 — 百行代码自制自动AC机器人日解千题攻占HDOJ
    redis Ok2
    ThinkPHP5 清除runtime缓存文件
    linux系统下使用xampp 丢失mysql root密码 只能远程访问,本地无法连接数据库
    yii2 验证规则使用方法
    thinkphp5 模型表关联
    PHP将base64数据流转换成图片并保存
    Win10下80端口被System占用导致Apache无法启动
    3. Git与TortoiseGit基本操作
  • 原文地址:https://www.cnblogs.com/zhaowei5/p/9854415.html
Copyright © 2020-2023  润新知