• DjanGo数据库方法


    单表的增删改查

    models.Department.objects.create(title="保安部")

    查询所有

     查询所有(查询一个:.first())
    res = models.Department.objects.all()
     <QuerySet [<Department: Department object>, <Department: Department object>]>
    for row in res:
     print(row.id, row.title)
    

    查询指定字段(values)

     #select title from department ;
    res = models.Department.objects.values("title").all()
    ### <QuerySet [{'title': '保安部'}, {'title': '开发部'}, {'title': '开发部'}]>
    for row in res:
        print(row['title'])
    

    查询指定字段(values_list元组)

    # res = models.Department.objects.values_list("title").all()
        # ### <QuerySet [('保安部',), ('开发部',), (' 吧开发部',)]>                                                                                                              
        # print(res)
    

    条件查询filter

     res = models.Department.objects.filter(id__lt = 3)   ### little then(小于3)
     res = models.Department.objects.filter(id__gt = 3)  ###  greater then(大于3)
     取第一条数据
     res = models.Department.objects.all().first()
     print(res)
    

    models.Department.objects.filter(id=3).delete()
    

    更新

    models.Department.objects.filter(id=2).update(title='xxxx')
    

    一对多表

     models.UserInfo.objects.create(uname = "zekai3", age=15, email="dddd@qq.com", ud_id=2)
    models.UserInfo.objects.create(uname = "zekai4", age=16, email="gggg@qq.com", ud_id=2)
     models.UserInfo.objects.create(uname = "zekai5", age=18, email="hhhh@qq.com", ud_id=1)
    
     info = {"uname":'zekai2', 'age':13, "email":'123@qq.com', "ud_id":2}
     models.UserInfo.objects.create(**info)
    
    

    正向查询
    res = models.UserInfo.objects.all()
    for row in res:
      print(row.id, row.uname, row.age, row.ud.title)
    
    反向查询
    ### 写法: 小写的表名_set.all()
    res = models.Department.objects.all()
    for row in  res:
     print(row.title, row.userinfo_set.all())
    

    神奇的双下画线

    用用于查询某一个人员的全部信息,包括这个人员在另一个表的外键的属性
    res = models.UserInfo.objects.values('id', 'uname', "ud__title").all()
        print(res)
    
    res = models.UserInfo.objects.values_list('id', 'uname', "ud__title").all()
        print(res)
    
  • 相关阅读:
    SDUT_1743 最优合并问题
    并查集路径压缩方法
    java定时器
    出路在哪里?出路在于思路!
    ztree学习
    sql
    java乱码问题详解值得收藏
    js 增加删除表格的行
    java DataBaseExecutor
    java增删改查
  • 原文地址:https://www.cnblogs.com/huanghongzheng/p/11196012.html
Copyright © 2020-2023  润新知