• day20 Django


    上节回顾

    1、Django请求的生命周期
    武彦涛:
    路由系统 -> 试图函数(获取模板+数据=》渲染) -> 字符串返回给用户

    2、路由系统
    王腾:
    /index/ -> 函数或类.as_view()
    /detail/(d+) -> 函数(参数) 或 类.as_view()(参数)
    /detail/(?P<nid>d+) -> 函数(参数) 或 类.as_view()(参数)
    /detail/ -> include("app01.urls")
    /detail/ name='a1' -> include("app01.urls")
    - 视图中:reverse
    - 模板中:{% url "a1" %}

    3、视图
    陈一波:
    FBV:函数
    def index(request,*args,**kwargs):
    ..

    CBV:类
    class Home(views.View):

    def get(self,reqeust,*args,**kwargs):
    ..

    获取用户请求中的数据:
    request.POST.get
    request.GET.get
    reqeust.FILES.get()

    # checkbox,
    ........getlist()

    request.path_info


    文件对象 = reqeust.FILES.get()
    文件对象.name
    文件对象.size
    文件对象.chunks()

    # <form 特殊的设置></form>


    给用户返回数据:
    render(request, "模板的文件的路径", {'k1': [1,2,3,4],"k2": {'name': '张扬','age': 73}})
    redirect("URL")
    HttpResponse(字符串)

    4.模板语言

    render(request, "模板的文件的路径", {'obj': 1234, 'k1': [1,2,3,4],"k2": {'name': '张扬','age': 73}})

    <html>

    <body>
    <h1> {{ obj }} </h1>
    <h1> {{ k1.3 }} </h1>
    <h1> {{ k2.name }} </h1>
    {% for i in k1 %}
    <p> {{ i }} </p>
    {% endfor %}

    {% for row in k2.keys %}
    {{ row }}
    {% endfor %}

    {% for row in k2.values %}
    {{ row }}
    {% endfor %}

    {% for k,v in k2.items %}
    {{ k }} - {{v}}
    {% endfor %}

    </body>
    </html>

    5、ORM
    吴世鹏
    闫利鹏
    a. 创建类和字段
    class User(models.Model):
    age = models.IntergerFiled()
    name = models.CharField(max_length=10)#字符长度

    Python manage.py makemigrations
    python manage.py migrate

    # settings.py 注册APP

    b. 操作
    王赛鹏


    models.User.objects.create(name='qianxiaohu',age=18)
    dic = {'name': 'xx', 'age': 19}
    models.User.objects.create(**dic)


    obj = models.User(name='qianxiaohu',age=18)
    obj.save()

    models.User.objects.filter(id=1).delete()

    models.User.objects.filter(id__gt=1).update(name='alex',age=84)
    dic = {'name': 'xx', 'age': 19}
    models.User.objects.filter(id__gt=1).update(**dic)

    models.User.objects.filter(id=1,name='root')
    models.User.objects.filter(id__gt=1,name='root')
    models.User.objects.filter(id__lt=1)
    models.User.objects.filter(id__gte=1)
    models.User.objects.filter(id__lte=1)

    models.User.objects.filter(id=1,name='root')
    dic = {'name': 'xx', 'age__gt': 19}
    models.User.objects.filter(**dic)

    v1 = models.Business.objects.all()
    #QuerySet内部元素都是对象
    #[obj(id,caption,code),obj(id,caption,code),obj(id,caption,code)]
    v2 = models.Business.objects.all().values('id','caption')
    # QuerySet 字典
    # [{'id': ,'caption': },{'id': ,'caption': },{'id': ,'caption': }]
    v3 = models.Business.objects.all().values_list('id','caption')
    # QuerySet turtle 元组
    # [(1,运维部),(2,开发),...]


    # 获取到的一个对象,如果不存在就报错
    models.Business.objects.get(id=1)
    对象或者None = models.Business.objects.filter(id=1).first()#存在则返回对象,不存在返回None


    外键:
    v = models.Host.objects.filter(nid__gt=0)
    v[0].b.caption ----> 通过.进行跨表

      外键:

        class UserType(models.Model):#自动生成id列,自增,主键

          caption = models.CharField(max_length=32)

          生成表

          id caption

          #1.普通用户

          #2.vip用户

          #3.游客

        

        class User(models.Model):

          age = models.IntergerField()

          name = models.CharField(max_length=10) #字符长度

          # user_type_id= model.IntergerField() #这样做没有约束,与表UserType没有关系

          user_type = models.ForeignKey("UserType", to_field='id') #与表UserType成外键关系,有约束

      

          自动生成表如下

          id    name    age    user_type_id

          1    laodong    23    2

          2    noname    23    3

    在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错:
    TypeError: __init__() missing 1 required positional argument: 'on_delete'

    一对多:

    #     v1 = models.Host.objects.filter(nid__gt=0)
    # # QuerySet 【hostobj(ip.host,另一个对象(...)),]
    # # for row in v1:
    # # print(row.nid, row.hostname,row.ip,row.port,row.business.caption)
    # v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','business_id','business__caption')
    # #QuerySet:[{},{},...]
    # v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','business_id','business__caption')
    # #QuerySet:[(),(),...]
    # return render(request,'host.html',{'v1':v1,'v2':v2,"v3":v3})

    Ajax

    $.ajax({
    url: '/host',
    type: "POST",
    data: {'k1': 123,'k2': "root"},
    success: function(data){
    // data是服务器端返回的字符串
    var obj = JSON.parse(data);
    }
    })

    $("#add_ajax_submit").click(function () {

                $.ajax(

    {                 url:'/ajax_add_app/',

                    {#data: {'user':123,'pwd':456},#}

                    {#data: {'user':123,'host_list':[1,2,3,4]},#}

                    data:$('#add_form').serialize(),

                    type:"POST",

                    dataType:'JSON',

                    traditional: true,

                    success: function (obj) {

                        {#JSON.parse(data)#}

                        console.log(obj)

                    },

                    error:function () {

                    }             })         })


    建议:永远让服务器端返回一个字典

    return HttpResponse(json.dumps(字典))

    多对多

    创建多对多:
    方式一:自定义关系表
    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()
    business = models.ForeignKey(to="Business",to_field="id",on_delete=models.CASCADE,)

    class Application(models.Model):
    name = models.CharField(max_length=32)

    class HostToApp(models.Model):
    hobj = models.ForeignKey(to="host",to_field="nid",on_delete=models.CASCADE,)
    aobj = models.ForeignKey(to="Application", to_field="id",on_delete=models.CASCADE,)

    HostToApp.objects.create(hobj_id=1,aobj_id=2)#通过操作类直接添加数据

    方式二:自动创建关系表

    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()
    business = models.ForeignKey(to="Business",to_field="id",on_delete=models.CASCADE,)

    class Application(models.Model):
    name = models.CharField(max_length=32)
      r = models.ManyToManyField("Host")#自动创建第三张表 只能帮你创建3列(id和两个表主键),不能添加额外数据

     #看不到多对多的那个表格,不能直接通过操作类来对表格进行操作

       obj = Application.objects.get(id=1)

       obj.name

       obj.r.add(1)#在第三张表中添加一个(1,1) 

       obj.r.add(2,3,4)

       obj.r.add(*[1,2,3,4])#通过列表操作

       obj.r.remove(1)#删除同样有三种方式

       obj.r.clear() #只清除id=1的

       obj.r.set([3,5,7]) #设置完只包括(1,3)(1,5,)(1,7)

  • 相关阅读:
    [LeetCode] 75. Sort Colors 颜色排序
    [LeetCode] 76. Minimum Window Substring 最小窗口子串
    OpenCV 2.4.10 Linux Qt Conifguration
    OpenCV2.4.10 Mac Qt Configuration
    [LeetCode] Combinations 组合项
    [LeetCode] 79. Word Search 词语搜索
    OpenCV count the number of connected camera 检测连接的摄像头的数量
    OpenCV 2.4.11 VS2010 Configuration
    Qt 程序和窗口添加图标
    [LeetCode] 80. Remove Duplicates from Sorted Array II 有序数组中去除重复项之二
  • 原文地址:https://www.cnblogs.com/laodong1983/p/9567045.html
Copyright © 2020-2023  润新知