zoukankan      html  css  js  c++  java
  • DjangoORM一对多&多对多操作

    简要说明

    通过操作对象的方式操作数据库

    详细步骤

    models.py的结构是:

    如果models.py中外键定义没有写 related_name=’student_teacher’, 可以直接用

    studentList = teacher.student_teacher.all() 可以改写成:
    
    teacher = Teacher.objects.get(id = 1)
    
    studentList = teacher.student_set.all()
    

    ============================================================================================

    from myblog.models import Student,Teacher

    def student_list(request):

    t = loader.get_template("student_list.html")
    
    #studentList = Student.objects.all()
    
    teacher = Teacher.objects.get(id = 1)
    
    studentList = teacher.student_teacher.all()
    
    c = Context({"studentList":studentList})
    
    return HttpResponse(t.render(c))
    

    数据库一对多的操作:

    查找:

    方法一:

    通过Student表来查:

    查找Student表中,teacher_id为1的老师名称

    studentList = Student.objects.all()
    

    模板中使用:

    student.teacher.name来获取外键的name属性值
    

    方法二:

    通过Teacher表来查:

    teacher = Teacher.objects.get(id = 1) #先查到id 为1 的teacher
    studentList = teacher.student_teacher.all() #通过外键查到studentlist

    新增

    方法一:

    通过teacher得到student_set来创建
    teacher.student_set.create(name = "tom",...)

    方法二:

    创造一个student对象,添加到teacher的student_set属性中
    student = Student(name = "tom",....)
    teacher.student_set.add(student)

    修改

    只删除student

    1. teacher = Teacher.objects.get(id = 1)
    2. student = teacher.student_set.get(id = 1)
    3. student.delete()

    删除和该teacher相关的所有student

    1. teacher = Teacher.objects.get(id = 1)
    2. student = teacher.student_set.get(id = 1)
    3. student.teacher.delete()

    数据库多对多操作:

    1. group = Group.objects.get(id = 1)
    2. studentList = group.members.all()
    3. groupList = student.group_set.all()
    4. MemberShip(group = newGroup, student=newStudent).save()




  • 相关阅读:
    Java:抽象类与接口
    OOP编程思想:类的设计原则
    Win10系统下设置Go环境变量和go语言开启go module
    Windows下Golang安装Iris框架
    AOS.JS 和基于Animation.css的收费库WOW.JS相似
    文本比价工具
    MySQL Order By Rand()效率
    datatable分页
    PHP面向对象之魔术方法
    PHP面向对象之序列化与反序列化
  • 原文地址:https://www.cnblogs.com/echorep/p/5423873.html
Copyright © 2011-2022 走看看